tags:

views:

84

answers:

2

The title says it all. 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 $.

Any help would be nice.

+5  A: 

This should work: ^!\w+

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

 foreach (Match  match in matches)
 {
      Console.WriteLine (match.Value);
 }
Nescio
that does work, but it only returns the first match
david
Yeah, it actually does work. I had to set the RegexOptions to multi-line.Thanks for the help ;)
david
you had to use Multiline? what does your regex string and what you want to match look like?
jb
The input text is a multi-line textbox, I want the output to be an array with all words that start with !. But it works now, good.
david
Careful, it will only match words at the beginning of a line.
Tim Pietzcker
+2  A: 

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.

Tim Pietzcker
+1 Good catch Tim! This is the real answer. Unfortunately, I answered before the full domain of the problem was made clear.
Nescio