tags:

views:

365

answers:

5

Wanna write a RegEx to validate a driving license.

if it doesn't start with (US, CA, CN) then it has to be followed with XX and after that with any number of Alpha numeric letters.

So for example if the driving license starts with GB then it has to be followed with XX GBXX12345363 However if it starts with US then we don't care what comes after it. USLA039247230

A: 
/^(?:(?:US|CA|CN)\w+|[[:alpha:]]{2}XX\w+)$/

I'm not sure if there's more validation that can be done, but this is what I get from what you wrote, not your examples (which seem to imply four letters followed by numbers).

Tanktalus
\w matches _ as well
Vinko Vrsalovic
A: 

You could use the Look Behind feature if your regex library allows it.

David Kemp
+3  A: 

Remember not everyone is familiar with that driving license notation, I'm assuming that what follows is the precise specification (you should really try to be very precise when asking for a regex else you'll get things you don't want):

  • Has to start with two capital letters
  • If those first two letters are either US, CA or CN, the rest has to be alphanumeric and of unspecified length
  • If those first two letters are none of US, CA or CN, then the next two letters have to be X, the rest after that has to be alphanumeric and of unspecified length

    ((US|CA|CN)[A-Za-z0-9]+|(?<!(US|CA|CN))[A-Z]{2}XX[A-Za-z0-9]+)

First part:

  • Matches one of US, CA or CN
  • One or more alphanumeric characters

Second part:

  • Negative lookbehind, doesn't start with US CA CN
  • Has two uppercase letters
  • There are two X characters
  • One or more alphanumeric characters

And it matches either the first part or the second one

Vinko Vrsalovic
The pipe in the outer parentheses makes the lookbehind completely unnecessary.
eyelidlessness
Also, I read "any number of alpha numeric" to mean * not +, but that's obviously up for debate. Poorly defined problem.
eyelidlessness
A: 
/^((US|CA|CN)[a-zA-Z\d]*|[a-zA-Z]{2}XX[a-zA-Z\d]*)$/
eyelidlessness
A: 

Seriously?!...seriously?....you guys are doing this kid's homework?....seriously?

Keng
Didn't notice the homework tag until you mentioned it.
DMKing