简体   繁体   English

如果后面没有模式,则正则表达式匹配

[英]regex match if not followed by pattern

I need to match string like:我需要匹配字符串,如:

RHS numberXnumberXnumber RHS编号X编号X编号

contained in strings like these: (all numbers can have the decimal part or not)包含在这样的字符串中:(所有数字都可以有小数部分或没有)

foo RHS 100x100x10 foo  
foo RHS 100.0x100x10 foo  
foo RHS 100.0x100.0x10.0 foo
foo RHS 100x100.0x100x10 foo  
foo RHS 10.0x100.0x10.0x10.0 foo  

I've written this:我写过这个:

RHS \\d+.?\\d?x\\d+.?\\d?x\\d+.?\\d RHS \\d+.?\\d?x\\d+.?\\d?x\\d+.?\\d

but this regex match also the first groups of number of the following string: foo RHS 100x100x100 x10 foo但是这个正则表达式也匹配以下字符串的第一组数字:foo RHS 100x100x100 x10 foo

how can I can I avoid that?我怎样才能避免这种情况? basically I don't want any match if there are four groups of number如果有四组数字,基本上我不想要任何匹配

The examples provided are incorrect.提供的示例不正确。 Most match line 4, and all match line 5. They're right that you need word boundaries and a negative lookahead, but they are missing a crucial piece.大多数匹配第 4 行,所有匹配第 5 行。他们是对的,您需要字边界和负前瞻,但他们缺少一个关键部分。

Regex matches word boundaries before and after dots.正则表达式匹配点前后的单词边界。 Meaning if the third number has a decimal, the search will not run to the end of the line, will not see the final x, but will match the string.意思是如果第三个数字有小数,搜索将不会运行到行尾,也不会看到最后的 x,但匹配字符串。

As a solution you need to use this negative lookahead that checks after the decimal for an x: (?!\\.?\\d?x)作为解决方案,您需要使用此负前瞻来检查 x 的小数点后: (?!\\.?\\d?x)

As well as wrapping the search in word boundaries: \\b...\\b以及将搜索包装在单词边界中: \\b...\\b

I tested the string below and it works.我测试了下面的字符串并且它有效。

\bRHS \d+\.?\d?x\d+\.?\d?x\d+\.?\d?(?!\.?\d?x)\b

Example: https://regex101.com/r/0nzHkN/2/示例: https : //regex101.com/r/0nzHkN/2/

Use this regular expression instead:请改用此正则表达式:

RHS \d+.?\d?x\d+.?\d?x\d+.?\d?(?!x)

Or a compact version of it:或者它的紧凑版本:

RHS (\d+.?\d?){3}(?!x)

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

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