W Simm
W Simm

Reputation: 55

How do i select only specific words?

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

Answers (3)

slf
slf

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

  • a word boundary
  • followed by either the word ant or the word bat
  • ending in a word boundary

A word boundary is probably what you would expect it to be, whitespace, end of a line, punctuation

Upvotes: 0

Jerin Joseph
Jerin Joseph

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

Paolo
Paolo

Reputation: 26074

Use a non capturing group with alternation:

(?:\bant\b|\bbat\b)

Upvotes: 2

Related Questions