Regular expression to match the whole word with special characters that don't work?

I discussed this question C #, Regex.Match whole words

It says that the word "\ bpattern \ b" is used for the whole word . This is great for matching the whole word without any special characters, since it is only for text characters!

I need an expression to match words with special characters. My code is as follows

class Program { static void Main(string[] args) { string str = Regex.Escape("Hi temp% dkfsfdf hi"); string pattern = Regex.Escape("temp%"); var matches = Regex.Matches(str, "\\b" + pattern + "\\b" , RegexOptions.IgnoreCase); int count = matches.Count; } } 

But it fails due to%. Do we have a workaround for this? There may be other special characters such as "space", "(',')", etc.

+6
source share
4 answers

The answer to this question can be found here.

regex expression to match the whole word

Thanks for all your answers!

0
source

If you have characters without words, you cannot use \b . You can use the following

 @"(?<=^|\s)" + pattern + @"(?=\s|$)" 

Change As Tim mentioned in the comments, your regular expression fails precisely because \b does not match the border between % and the space next to it, because both of them are not - word characters. \b matches only the boundary between a word character and a character other than a word.

Read more about word boundaries here .

Explanation

 @" (?<= # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) # Match either the regular expression below (attempting the next alternative only if this one fails) ^ # Assert position at the beginning of the string | # Or match regular expression number 2 below (the entire group fails if this one fails to match) \s # Match a single character that is a "whitespace character" (spaces, tabs, and line breaks) ) temp% # Match the characters "temp%" literally (?= # Assert that the regex below can be matched, starting at this position (positive lookahead) # Match either the regular expression below (attempting the next alternative only if this one fails) \s # Match a single character that is a "whitespace character" (spaces, tabs, and line breaks) | # Or match regular expression number 2 below (the entire group fails if this one fails to match) $ # Assert position at the end of the string (or before the line break at the end of the string, if any) ) " 
+5
source

If the template may contain characters that are special for Regex, first run it with Regex.Escape .

You did this, but don’t avoid the line you are viewing β€” you don’t need it.

+3
source
 output = Regex.Replace(output, "(?<!\w)-\w+", "") output = Regex.Replace(output, " -"".*?""", "") 
+1
source

All Articles