Regex expression to match whole word with special characters not working ? [duplicate]

二次信任 提交于 2019-12-04 07:57:26

If you have non-word characters then you cannot use \b. You can use the following

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

Edit: As Tim mentioned in comments, your regex is failing precisely because \b fails to match the boundary between % and the white-space next to it because both of them are non-word characters. \b matches only the boundary between word character and a non-word character.

See more on 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)
)
"

If the pattern can contain characters that are special to Regex, run it through Regex.Escape first.

This you did, but do not escape the string that you search through - you don't need that.

output = Regex.Replace(output, "(?<!\w)-\w+", "")
output = Regex.Replace(output, " -"".*?""", "")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!