/^.*?cat.*?mat.*?$/m
Using the m
modifier (which ensures the beginning/end metacharacters match on line breaks rather than at the very beginning and end of the string):
^
matches the line beginning
.*?
matches anything on the line before...
matches a word boundary the first occurrence of a word boundary (as @codaddict discussed)
- then the string
cat
and another word boundary; note that underscores are treated as "word" characters, so _cat_
would not match*;
.*?
: any characters before...
- boundary,
mat
, boundary
.*?
: any remaining characters before...
$
: the end of the line.
It's important to use
to ensure the specified words aren't part of longer words, and it's important to use non-greedy wildcards (.*?
) versus greedy (.*
) because the latter would fail on strings like "There is a cat on top of the mat which is under the cat." (It would match the last occurrence of "cat" rather than the first.)
* If you want to be able to match _cat_
, you can use:
/^.*?(?:|_)cat(?:|_).*?(?:|_)mat(?:|_).*?$/m
which matches either underscores or word boundaries around the specified words. (?:)
indicates a non-capturing group, which can help with performance or avoid conflicted captures.
Edit: A question was raised in the comments about whether the solution would work for phrases rather than just words. The answer is, absolutely yes. The following would match "A line which includes both the first phrase and the second phrase":
/^.*?(?:|_)first phrase here(?:|_).*?(?:|_)second phrase here(?:|_).*?$/m
Edit 2: If order doesn't matter you can use:
/^.*?(?:|_)(first(?:|_).*?(?:|_)second|second(?:|_).*?(?:|_)first)(?:|_).*?$/m
And if performance is really an issue here, it's possible lookaround (if your regex engine supports it) might (but probably won't) perform better than the above, but I'll leave both the arguably more complex lookaround version and performance testing as an exercise to the questioner/reader.
Edited per @Alan Moore's comment. I didn't have a chance to test it, but I'll take your word for it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…