Reputation: 55
With the string ant apple bat
I want to select only ant
and bat
without selecting apple or any white space.
I've tried a few different things like;
\bant\b\bbat\b
or
ant\bbbat\b
or
(\b(ant)\b.*\b(bat)\b)
or
ant(?:.*)bat
or
ant(?:\sapple\s)bat
or
(ant)*[^a-z\s]*(bat)
I know the above examples are stupid but i'm just messing around on a regex tester trying to figure it out. I did regex before and I figured it out but can't seem to remember how i did it. Seems pretty simple just to select "ant" and "bat" but obviously not. Is there some way to deselect a match or to remove part of the match?
Upvotes: 1
Views: 95
Reputation: 22767
If you just want two different words, that looks like this:
\b(ant|bat)\b
The \b
is a word boundary
The parenthesis is a group
The pipe |
is an or statement
ant
or the word bat
A word boundary is probably what you would expect it to be, whitespace, end of a line, punctuation
Upvotes: 0
Reputation: 1097
I guess you've understood it wrong. A single regex match will match only contiguous text. A simple regex like ant|bat
with either match ant or bat. But if you want to match ant and bat ignoring the text in between would not work.
When using regex with any programming languages like python or java, you would loop through the multiple matches and perform the action accordingly.
Upvotes: 0