I have a bunch of 4XX status codes and I want to match all except 400 and 411.
What I currently have so far:
/4\d{2}(?!400|411)/g
Which according to regexer:
- Matches a 4XX
- Should specify a group that cannot match after the main expression (but it is here where my expression is failing).
CodePudding user response:
The expression 4\d{2}(?!400|411)
First matches a 4
and then 2 digits. After the matching, it asserts not 400 and 411 directly to the right.
Instead, you can match 4
and first assert not 00 or 11 directly after it.
4(?!00|11)\d{2}
Or without partial word matches using word boundaries \b
:
\b4(?!00|11)\d{2}\b
See a regex demo
CodePudding user response:
If this is for a RegEx embedded in a programming language, I'd recommend using string comparisons or converting the status code to a number if it isn't already to then do number comparisons.
If you're forced to use RegEx, another, arguably less readable option (that does however make use of fewer RegEx features and is thus more portable): 4(0[1-9]|[1-9][02-9])
- If the second character is a zero, the third character must be a nonzero digit;
- If the second character is a one, the third character must be any digit other than one
If you don't want/need a capturing group, change the RegEx to 4(?:...)
.