sorin
sorin

Reputation: 170826

Regexp to detect a word only if it is not part of longer word?

I am looking for a regex that would match a word only of it is not part of a longer word.

Let's assume that the word is `failure', so here are some examples

Mainly failure string needs not to have any [\d\w-_] around it in order to be considered part

Upvotes: 1

Views: 91

Answers (3)

Bill K
Bill K

Reputation: 62789

Not a very good case for Regex.

Why not String.split to break it into words, then compare each word to your target (Since what you are saying is that it should only match if isolated by spaces).

Well, String.split DOES use Regex, but it's a lot more controlled and you really only need the default split on space, or maybe you want to add periods (So your second example would match).

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

Since you're including the dash in the group of characters that constitute a word, you can't do it with word boundaries; you need lookaround assertions (which are supported by Java):

(?<![\w-])failure(?![\w-])

should do it.

Explanation:

(?<![\w-])  # Assert no alphanumeric or dash before the current position
failure     # Match "failure"
(?![\w-])   # Assert no alphanumeric or dash after the current position

Upvotes: 2

chaos
chaos

Reputation: 124365

If your flavor of regex supports it, you can use \b to match on a word break, e.g. /\bfailure\b/.

Upvotes: 1

Related Questions