tags:

views:

47

answers:

3

I am trying to make a regex that matches all occurrences of words that are at the start of a line and begin with #.

For example in:

#region #like
#hey

It would match #region and #hey.

This is what I have right now:

^#\w*

I apologize for posting this question. I'm sure it has a very simple answer, but I have been unable to find it. I admit that I am a regex noob.

A: 

Use this regex

^#.+?\b

.+ will ensure at least one character after # and \b indicates word boundry. ? adds non-greediness to the + operator so as to avoid matching whole string #region #like

Gopi
+5  A: 

What you've got should work, depending on what flags you pass for RegexOptions. You need to make sure you pass RegexOptions.Multiline:

var matches = Regex.Matches(input, @"^#\w*", RegexOptions.Multiline);

See the documentation I linked to above:

Multiline Multiline mode. Changes the meaning of ^ and $ so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.

Dean Harding
Wow. Thanks. I knew I was doing something stupid. Will accept your answer as soon as I can.
Justin
+1  A: 

The regex looks fine, make sure you're using a verbatim string literal (@ prefix) to define your regex, i.e. @"^#\w*" otherwise the backslash will be treated as an escape sequence.

cxfx