tags:

views:

134

answers:

3

Quick regex question (since i am horrible at it)

I have a field that can only have either:

XXXXXXXXXX or XXXXXX-XXXX where X is a real number.

Bonus if the regex works well with PHP's regex functions.

The Answer:

Here's the code from RoBorg's answer, for those interested.

if(!preg_match("/^\d{6}-?\d{4}$/", $var))
{
    // The entry didn't match
}
A: 

If you want a specific number (the question wording was originally somewhat ambiguous), search for (e.g.):

^123456-?7890$

If searching for any 10 digit number with that format, search for:

^\d{6}-?\d{4}$

The ? qualifier after the dash means "0 or 1 occurrences of the preceding entity"

Alnitak
+8  A: 
/^\d{6}-?\d{4}$/

That's

^     Start of string
\d{6} a digit, repeated exactly 6 times
-?    an optional "-"
\d{4} a digit, repeated exactly 4 times
$     end of string
Greg
+1  A: 

Just quickly, it'd be something like this: \d{6}-?\d{4}

You may have to escape the hyphen in PHP.

Matt Grande