Reputation: 10949
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
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
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
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/
Upvotes: 3