Reputation: 1778
what pattern should i use in regex if i want to match the first pattern but then i want to unmatch the second pattern.
for example i want to match the string 'id' followed by decimal as long as that decimal is not 6 or 9.
so it should match id1,id2,id3 ...
etc but not id6
and id9
.
I tried this pattern and it's not working :
"id(\d|(?!6|9))"
Upvotes: 0
Views: 120
Reputation: 11032
Its not the best solution but you can also do this using positive look ahead
as
\bid(?=\d)(?:\d\d+|[^69])\b
Regex Breakdown
\b #word boundary
id #Match id literally
(?=\d) #Find if the next position contains digit (otherwise fails)
(?: #Non capturing group
\d\d+ #If there are more than one digits then match is success
| #OR (alternation)
[^69] #If its single digit don't match 6 or 9
) #End of non capturing group
\b
If you want to check id
is not followed by 6
or 9
and you want to accept cases like id16
but not id61
, then you can use
\bid(?=\d)[^69]\d*\b
Upvotes: 3
Reputation: 626754
The id(\d|(?!6|9))
pattern matches id
followed with any 1 digit or if there is no 6
or 9
. That alternation (\d
or (?!6|9)
) allows id6
and id9
because the first alternative "wins" in NFA regex (i.e. the further alternatives after one matches are not tested against).
If you need to only exclude id
matches with 6
or 9
use
\bid(?![69]\b)\d+\b
See the regex demo
If you want to avoid matching all id
with 6
and 9
following it, use
\bid(?![69])\d+
See another regex demo.
Here, \d+
matches one or more digits, \b
stands for a word boundary (the digits should be preceded and followed with non-"word" characters), and the (?![69])
lookahead fails the match if there is 6
or 9
after id
(with or without a word boundary check - depending on what you need).
UPDATE
If you need to exclude the id
whose number does not start with 6
or 9
, you can use
\bid[0-578]\d*
(demo)
Based on Shafizadeh's comment.
Upvotes: 1
Reputation:
You can use negative lookahead
like this.
Regex: \bid(?![69])\d\b
Explanation:
\b
ensures the word boundary.
(?![69])
negative lookahead makes sure that number is not 6 or 9.
\d
matches a single digit after id
.
Upvotes: 3