Reputation: 385
I need to match string like:
RHS numberXnumberXnumber
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
but this regex match also the first groups of number of the following string: foo RHS 100x100x100x10 foo
how can I can I avoid that? basically I don't want any match if there are four groups of number
Upvotes: 3
Views: 2914
Reputation: 1974
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.
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.
As a solution you need to use this negative lookahead that checks after the decimal for an x: (?!\.?\d?x)
As well as wrapping the search in word boundaries: \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/
Upvotes: 3
Reputation: 11336
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)
Upvotes: 0