简体   繁体   English

Perl正则表达式-排除模式

[英]Perl Regex - Exclude a pattern

for which I have to replace all numbers with a text tag 'NUMBER'. 为此,我必须将所有数字替换为文本标记“ NUMBER”。 but there is a certain condition it shouldn't be changed, when ever a number exists with an underscore in it .. (eg 123_456). 但是在一定条件下,如果存在带下划线的数字,则不应更改它(例如123_456)。 I am using 我在用

s/\d+/NUMBER/g

but it changes the likes of 123_456 to NUMBER_NUMBER. 但会将喜欢的123_456更改为NUMBER_NUMBER。 Is there a way to exclude it? 有办法排除它吗? The [^xyz] pattern might not work, as it negates a single character at a time (this is my understanding). [^ xyz]模式可能不起作用,因为它一次否定一个字符(这是我的理解)。 Any ideas ? 有任何想法吗 ? Input file sample is: The last number shouldn't be changed. 输入文件示例为:不应更改最后一个数字。

received for code:3
received for code:1
received for code:9
received for code:33
received for code:4
received for code:323_456

您可以使用单词边界来避免匹配的数字,后跟一个下划线:

s/\b\d+\b/NUMBER/g

Match only groups of digits that don't have a _ before or after: 仅匹配之前或之后没有_的数字组:

s/(?<![_0-9])[0-9]+(?![_0-9])/NUMBER/g;

Note that \\d isn't usually what people want, since it can match many more characters that are characterized as digits than just 0-9. 请注意, \\d通常不是人们想要的,因为它可以匹配更多的数字字符,而不仅仅是0-9。 (Though the /a flag does make it mean just 0-9.) (尽管/ a标志的确使它仅表示0-9。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM