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.
5 Answers
Just don't anchor your pattern:
/Test/
The above regex will check for the literal string "Test" being found somewhere within it.
4 Comments
^.*Test.*$dayRegx = /^.*((Monday)|(Tuesday)|(Wednesday)|(Thursday)|(Friday)|(Saturday)|(Sunday)).*$/gi; const containsDay = dayRegx.test(someStr);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.
2 Comments
\b represents a "word boundary", that is, something which separates two words (e.g. a space)." \b does not match a space; it is an assertion which matches between characters (or at the beginning or end of a line, in most cases).For Java use this: ^.*Test.*$.
It reads as: The string begins (^) then any character (.) can be repeated zero or more times (*) then Test and then again any character (.) repeated zero or more times (*) and the string ends ($).
3 Comments
Depending on your flavor of regular expression - the exact details of regex capabilities vary depending on the language.
I will give javascript examples.
If you don't care about null safety...
str = "blah"
str.match(/a/)
// [ 'a', index: 2, input: 'blah', groups: undefined ]
Case-sensitive
/test/.test("does this string contain the word testtesttest")
// true
Case-insensitive
/test/i.test("Test")
Case-insensitive, ANY word
/\b\w+\b/i.test("bLAH")
// true
Comments
I'm a few years late, but why not this?
[Tt][Ee][Ss][Tt]
5 Comments
[Aa] pattern for every letter and it would get pretty ugly pretty fast.. So I tried /[.]/. but /./ didn't work./test/i.test(inputString) where the /i on the end makes it case-insensitive (javascript)/\./