C# Regex getting words that start with?

你离开我真会死。 提交于 2021-02-08 08:18:14

问题


How can I use a regular expression to get words that start with ! ? For example !Test.

I tried this but it doesn't give any matches:

@"\B\!\d+\b"

Although it did work when I replaced the ! with $.


回答1:


This should work: ^!\w+

 MatchCollection matches = Regex.Matches (inputText, @"^!\w+");

 foreach (Match  match in matches)
 {
      Console.WriteLine (match.Value);
 }



回答2:


I'd say that your regex was quite OK already, you just need to use \w (alphanumeric character) instead of \d (digit):

@"\B!\w+\b"

will match any word that is immediately preceded by a ! unless that ! itself is preceded by a word itself (that's what the \B asserts). Using a ^ instead will limit the matches to words that start at the beginning of a line which might not be what you want.

So this will match all the words including exactly one preceding ! in this line:

!hello !this ...!will !!!be !matched!

but none of the words in this line:

this! won't!be matched!!! 

You could also drop the \B altogether if you don't mind matching !that in this!that.



来源:https://stackoverflow.com/questions/3952032/c-sharp-regex-getting-words-that-start-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!