Reputation: 199
I need to regex-match numbers in a certain pattern which works already, but only if there is not (+
right in front of it.
Example Strings I want to have a valid match within: 12
, 12.5
, 200/300
, 200/300/400%
, 1/2/3/4/5/6/7
Example Strings I want to have no valid match within: (+10% juice)
, (+4)
I can already get all the valid matches with (\d+[/%.]?)+
, but I need help to exclude the example Strings I want to have no valid match in (which means, only match if there is NOT the String (+
right in front of the mentioned pattern).
Can someone help me out? I have already experimented with the !
(like ?!(\(\+)(\d+[/%.]?)+
) but for some reason I can't it to work the way I need it.
(You can use http://gskinner.com/RegExr/ to test regex live)
EDIT: I did maybe use wrong words. I don't want to check if the searchstring does start with (+
but I want to make sure that there is no (+
right in front of my String.
Try regexr with the following inputs:
Match: (\d+[/%.]?)+
Check the checkbox for global
(to search for more than one match within the text)
Text:
this should find a match: 200/300/400
this shouldnt find any match at all: (+100%)
this should find a match: 40/50/60%
this should find a match: 175
Currently it will find a match in all 4 lines. I want a regex that does no longer find a match in line 2.
Upvotes: 0
Views: 378
Reputation: 3588
The regex construct you are wanting is "Negative Lookbehind" - See http://www.regular-expressions.info/lookaround.html. A negative lookbehind is defined like (?<!DONTMATCHME)
where DONTMATCHME is the expression you don't want to find just before the next bit of the expression. Crutially, the lookbehind bit is not considered part of the match itself
Your expression should be:
(?<![+\d/\.])(\d+[/%.]?)+
Edit - changed negative lookbehind to any character that is not a + or another digit!
Edit #2 - moved the lookbehind outside the main capture brackets. Expanded the range of not acceptable characters before the match to include /
& .
Upvotes: 1