Reputation: 2590
For this example let's say we have following keywords:
banana
apple.
apple-
apple party #(double space)
apple pie
sweet apple pie
apple
apple 34
How to make regex match only "apple" words without special characters and more then one space? So from example above it would only match last 4 and ignore first 4.
Upvotes: 2
Views: 43
Reputation: 44833
Try this:
\bapple\b(?!\s{2}|\S)
This works by requiring a word boundary (\b
) before and after the word and excluding matches followed by two spaces or a non-whitespace character.
Edit: You indicated in your comment that you want to match the entire line. This is easy; just add .*
before and after the regex above, like this:
.*?\bapple\b(?!\s{2}|\S).*
Demo (I added a ?
to the first .*
to avoid performance problems due to backtracking.)
Edit 2: Based on additional comments: you also want to exclude matches like apple . com
. This is a little trickier, but this regex will do it:
(?!.*?\bapple\b(?:\s{2}|\s*[.\/,<>-])).*?\bapple\b.*
Demo. This one works by using a negative lookahead. The group (?!.*?\bapple\b(?:\s{2}|\s*[.\/,<>-]))
means that the line must not contain apple
with either (a) 2+ spaces or (b) any number of spaces and a character in the set ./,<>-
after it. This should do what you want.
Upvotes: 3