tags:

views:

155

answers:

5

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!

+4  A: 

"$" 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.

Chamelaeon
+5  A: 

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.

Tyler McHenry
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.
Alan Moore
+1  A: 

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

FerranB
+1  A: 

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.

Andrew Shepherd
+3  A: 

Are the phone numbers always on thier 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 $.

Ariel