\D在Perl正则表达式中做什么

时间:2022-12-28 22:33:13

In some code I am maintaining, I have found the expression:

在我维护的一些代码中,我找到了这样的表达式:

$r->{DISPLAY} =~ s/\Device//s;

What surprises me is that it matches both device and Device!

令我惊讶的是,它同时与设备和设备相匹配!

I have not found any mention of \D in the documentation, only \d.

我在文档中没有发现任何关于\D的内容,只有\D。

Can someone clarify please...

谁能澄清请…

3 个解决方案

#1


19  

\D is the negation of \d, i.e. it matches anything that is not a digit.

\D是对\D的否定,也就是说,它匹配任何不是数字的东西。

#2


11  

In that regex, \D looks like a typo. It works for both d and D, only because it matches any character that is not a digit (0-9).

在那个regex中,\D看起来像一个错误。它对d和d都适用,只是因为它匹配任何不是数字(0-9)的字符。

A more appropriate regex (if the intent is to match "device" or "Device"), is:

更合适的regex(如果目的是匹配“设备”或“设备”)是:

s/(d|D)evice// # one way
s/[dD]evice//  # another way

The s option is also a bit odd. From perldoc perlop

s选项也有点奇怪。从perldoc perlop

s   Treat string as single line. (Make . match a newline)

And there is no such matching going on in that line.

这条线上没有这样的匹配。

#3


2  

You already have an answer, However, there's documentation in perldoc perlrecharclass about it. See the information about Backslash sequences.

但是,您已经有了答案,在perldoc perlrecharclass中有关于它的文档。参见有关反斜杠序列的信息。

It's also mentioned in perldoc perlrequick and in the regular perldoc perlretut under Using character classes. However, in those two sections, it's rather buried.

在perldoc perlrequick和常规perldoc perlretut中也提到这一点。然而,在这两个部分,它被埋了。

#1


19  

\D is the negation of \d, i.e. it matches anything that is not a digit.

\D是对\D的否定,也就是说,它匹配任何不是数字的东西。

#2


11  

In that regex, \D looks like a typo. It works for both d and D, only because it matches any character that is not a digit (0-9).

在那个regex中,\D看起来像一个错误。它对d和d都适用,只是因为它匹配任何不是数字(0-9)的字符。

A more appropriate regex (if the intent is to match "device" or "Device"), is:

更合适的regex(如果目的是匹配“设备”或“设备”)是:

s/(d|D)evice// # one way
s/[dD]evice//  # another way

The s option is also a bit odd. From perldoc perlop

s选项也有点奇怪。从perldoc perlop

s   Treat string as single line. (Make . match a newline)

And there is no such matching going on in that line.

这条线上没有这样的匹配。

#3


2  

You already have an answer, However, there's documentation in perldoc perlrecharclass about it. See the information about Backslash sequences.

但是,您已经有了答案,在perldoc perlrecharclass中有关于它的文档。参见有关反斜杠序列的信息。

It's also mentioned in perldoc perlrequick and in the regular perldoc perlretut under Using character classes. However, in those two sections, it's rather buried.

在perldoc perlrequick和常规perldoc perlretut中也提到这一点。然而,在这两个部分,它被埋了。