Problem with regular expressions i .NET

  • Thread starter Thread starter Arne
  • Start date Start date
A

Arne

Hi,

I'm trying to recognise phone numbers on the following format using
regular expressions: +47 123 45 678

This should be recognised by the following regular expression:
+47 \d{3} \d{2} \d{3} but it's not.

This regular expression: +47 \d{2} \d{2} \d{2} \d{2} DOES recognise
the following phone number: +47 12 34 56 78

Any ideas why the first doesn't work?
I'm using C#.

Thanks in advance, regards,
Lars D.
 
Arne,

The "+ " in a regular expression is treated as a quantifier; means one or more occurrence of the preceding character.

Since there is no preceding character before "+", it should give you a run time error of bad quantifier.

Regex re=new Regex(@"+47 \d{2} \d{2} \d{2} \d{2}");
if(re.IsMatch("+47 12 34 56 78"))
Console.WriteLine("Matched");

If you want the + character to be recognized literally, just escape it with a backslash.

This should run

Regex re=new Regex(@"\+47 \d{2} \d{2} \d{2} \d{2}");
if(re.IsMatch("+47 12 34 56 78"))
Console.WriteLine("Matched");

Thanks,

Fakher Halim
Technical Architect, TPG
 
Sorry, that was a typo in my original post. I actually have escaped
the "+" character. I get no error messages, I just can't get any
matches for phone numbers on the following format: +47 123 45 678
Thank you for your reply.
 
Arne,
The following code prints "Matched" on my console. Doesn't it work on yours?
Would you copy pasted the actual code that is failing?

Regex re=new Regex(@"\+47 \d{2} \d{2} \d{2} \d{2}");
if(re.IsMatch("+47 12 34 56 78"))
Console.WriteLine("Matched");

Fakher Halim
 
For "+47 123 45 678", the "\+47 \d{2} \d{2} \d{2} \d{2}" would not match. if
you want to allow 2 to three digit in some place, use "\d{2,3}" instead of
\d{2}.
Fakher Halim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

regular expression NxM 9
Regular expression 3
Regular expression 4
Regular expression 5
need some finer tuning on the regular expression 9
regular expression 7
Regular Expression Help 1
One more regular expression 4

Back
Top