REGEX help

  • Thread starter Thread starter pfeifest
  • Start date Start date
P

pfeifest

Hello-

How would I validate the following statement in a REGEX validation?


Thanks-


pfeifest


***********************
a 7-digit number starting with an 8 or an 8-digit number starting with
a 5
***********************
 
pfeifest said:
Hello-

How would I validate the following statement in a REGEX validation?

***********************
a 7-digit number starting with an 8 or an 8-digit number starting with
a 5
***********************

the actual regular expressions would be (i believe) this:

^(8\d{6})$
^(5\d{7})$

.... i think. definitely something like that. You'll need to escape the
backslashes when you actually build the Pattern object.

if it will help you later, i'll explain. they read like this:
^ - at the very beginning of the string,
( - start remembering what you match,
8 - look for a number eight,
\d{6} - followed by 6 other digits,
) - don't remember anything after this,
$ - and only if the number touches the end of the string.

similarly for the second regex.

If you don't necessarily want to match these numbers on their own, for
instance, if they're part of a sentence, remove the ^ and $, and maybe
add spaces before the 8 and after the \d{6}.

I highly recommend O'Reilly's "Mastering Regular Expressions" by Jeffrey
Friedl. I used to work with him at Yahoo! and the dude knows regular
expressions better than anyone I've ever met.

Hope that helps.
 
Thanks Jeremiah. Is there a way I can do that in the same statement
though? Basically not two lines - just one. I insert that into a db
field and validate it in our business layer.

- pfeifest
 
pfeifest said:
Thanks Jeremiah. Is there a way I can do that in the same statement
though? Basically not two lines - just one. I insert that into a db
field and validate it in our business layer.

Sure - use the alternation operator:

^((8\d{6})|(5\d{7}))$

Here's some sample code:

using System;
using System.Text.RegularExpressions;

class Test
{
static readonly string[] Examples=
{
"1234567", "8123456", "51234567", "81234567", "5123456",
"other123", "o8123456", "812346o"
};

static void Main()
{
Regex regex = new Regex(@"^((8\d{6})|(5\d{7}))$");
foreach (string x in Examples)
{
Console.WriteLine ("{0}: {1}", x, regex.IsMatch(x));
}
}
}
 

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

Back
Top