osk
osk

Reputation: 810

Regex to match an exact word which can only have spaces etc in front or after it

I am trying to figure out a regex that will match a certain word, where the word cannot be a part of any other "word".

So this word that I am trying to match can only have spaces, tabs or linebreaks in front or after it.

I have tried the following:

s\sWORD$
s\sWORD\s
^WORD\s

Upvotes: 1

Views: 1906

Answers (1)

anubhava
anubhava

Reputation: 785128

this word that I am trying to match can only have spaces, tabs or linebreaks in front or after it.

One of these regex patterns should work for you:

(?<=\s|^)WORD(?=\s|$)
(?<!\S|^)WORD(?!\S)

First one means WORD must be preceded by whitespace or line start and it must be followed by whitespace or line end.

Second one means WORD must NOT be preceded by non-whitespace and it must NOT be followed by a non-whitespace.

Java examples:

"WORD abc".matches(".*?(?<=\\s|^)WORD(?=\\s|$).*"); // true

"WORD".matches(".*?(?<=\\s|^)WORD(?=\\s|$).*"); // true

"WORD-abc".matches(".*?(?<=\\s|^)WORD(?=\\s|$).*"); // false

"some-WORD".matches(".*?(?<=\\s|^)WORD(?=\\s|$).*"); // false

Upvotes: 4

Related Questions