I have the following code. The idea is to detect whole words.
bool contains = Regex.IsMatch("Hello1 Hello2", @"\bHello\b"); // yields false
bool contains = Regex.IsMatch("Hello Hello2", @"\bHello\b"); // yields true
bool contains = Regex.IsMatch("Hello: Hello2", @"\bHello\b"); **// yields true, but should yield false**
Seems that Regex is ignoring the colon. How can I modify the code such that the last line will return false?
A colon has no special meaning in Regular Expressions, it just matches a literal colon.
In most regex implementations (including Java's), : has no special meaning, neither inside nor outside a character class. where ,-: matches all ascii characters between ',' and ':' . Note that it still matches the literal ':' however! By placing - at the start or the end of the class, it matches the literal "-" .
Semicolon is not in RegEx standard escape characters. It can be used normally in regular expressions, but it has a different function in HES so it cannot be used in expressions. As a workaround, use the regular expression standard of ASCII.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
\b
means "word boundary". :
is not part of any word, so the expression is true.
Maybe you want an expression like this:
(^|\s)Hello(\s|$)
Which means: the string "Hello", preceded by either the start of the expression or a whitespace, and followed by either the end of the expression or a whitespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With