0

This is almost certainly something really silly that I've overlooked but I'm stumped. The following C# style expression is supposed to match phones numbers (a limited subset of them, but this is just testing...):

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

The search string is as follows:

978-454-0586\r\nother junk\r\nmore junk\r\nhttp://www.google.com\r\n

The expression matches the phone number when in isolation, however not when next to other stuff. For example, if I lop off everything after the phone it works just great.

How can I modify the expression so that it matches the phone number and doesn't get hung up on the rest of the junk?

Thanks!

2
  • Haha I like how we all answered at the same time. I've marked mine for deletion to declutter the page. Commented Mar 19, 2009 at 0:34
  • well looks like you're all correct. thanks a bunch! Commented Mar 19, 2009 at 0:39

5 Answers 5

5

The ^ and $ symbols mean "beginning of line" and "end of line" respectively. Get rid of them if you want to match in the middle of a line.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, the phone number is on its own line; see the \r\n after it? If you were to apply the MULTILINE modifier as advised by Ariel, the regex would work just fine.
4

"$" in a regular expression matches the end of a line. If you remove that, the regexp should work correctly, though if you have "Foo978-454-0586", it won't work, since "^" matches the start of a line.

Comments

3

Are the phone numbers always on their own lines? If so add RegexOptions.Multiline to your Regex constructor. Without that the regex.match is using the beginning and end of the string for ^ and $.

Comments

1

The $ means end of string, not end of line.

Comments

1

The problem is that "^" and "$" forces it to only match on the start of the string and the end of the string.

Remove those two tags and see how you go.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.