Regex for string contains?

2020-05-11 11:04发布

What is the regex for simply checking if a string contains a certain word (e.g. 'Test')? I've done some googling but can't get a straight example of such a regex. This is for a build script but has no bearing to any particular programming language.

标签: regex
3条回答
▲ chillily
2楼-- · 2020-05-11 11:34

Assuming regular PCRE-style regex flavors:

If you want to check for it as a single, full word, it's \bTest\b, with appropriate flags for case insensitivity if desired and delimiters for your programming language. \b represents a "word boundary", that is, a point between characters where a word can be considered to start or end. For example, since spaces are used to separate words, there will be a word boundary on either side of a space.

If you want to check for it as part of the word, it's just Test, again with appropriate flags for case insensitivity. Note that usually, dedicated "substring" methods tend to be faster in this case, because it removes the overhead of parsing the regex.

查看更多
神经病院院长
3楼-- · 2020-05-11 11:37

Just don't anchor your pattern:

/Test/

The above regex will check for the literal string "Test" being found somewhere within it.

查看更多
Anthone
4楼-- · 2020-05-11 11:43

I'm a few years late, but why not this?

[Tt][Ee][Ss][Tt]
查看更多
登录 后发表回答