C# Regex getting words that start with?
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 d开发者_如何学编程id work when I replaced the !
with $
.
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
.
This should work: ^!\w+
MatchCollection matches = Regex.Matches (inputText, @"^!\w+");
foreach (Match match in matches)
{
Console.WriteLine (match.Value);
}
精彩评论