Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex and the colon (:)

Tags:

c#

regex

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?

like image 812
Liviu Mandras Avatar asked Nov 09 '10 14:11

Liviu Mandras


People also ask

Does colon mean anything in regex?

A colon has no special meaning in Regular Expressions, it just matches a literal colon.

How do you use a colon in regex?

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 "-" .

How do you match a semicolon in regex?

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.

What is difference [] and () in regex?

[] 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 .


1 Answers

\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.

like image 85
Fábio Batista Avatar answered Nov 11 '22 17:11

Fábio Batista