Doua Beri
Doua Beri

Reputation: 10949

regex match based on condition

I'm having the following string

test test.a test.b test.a.b test2.a test2 test2.a.b

and the following regex

/(test(\.)(\S*)?)/gi

This returns the following test.a test.b test.a.b What I want is to return test as well.

If I make (\.)? optional it returns test2.a as well and I don't want that.

What I'm looking for is to have a condition. If there is dot after test return test.whatever.else else if there is space after test return test , else do not match anything.

Live example : https://regex101.com/r/ZendrY/3

Upvotes: 1

Views: 130

Answers (3)

topalkata
topalkata

Reputation: 2098

You can try adding \b for matching the word end as well, e.g.:

/(test(\.?\b)(\S*)?)/ig

... or a positive lookahead:

/(test?(?=[\. ])(\S*))/ig

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

You can use alternation so that test is followed by either a dot or a space rather than making the dot optional:

/test(?= )|(test(\.)(\S*)?)/gi

Upvotes: 0

anubhava
anubhava

Reputation: 785256

You can use this regex with an optional match of DOT followed by 1 or more non-space character after test and wrapped by word boundary on either side:

/\btest(?:\.\S+)?\b/

RegEx Demo

Upvotes: 3

Related Questions