goodyzain
goodyzain

Reputation: 673

Regex for allowing two numbers(0-9) anywhere in the charecters

I am new newbie to regex world,and i am trying to get regex for the following....

A user can have in the following manner

  1. goodyzain
  2. 1goodyzain
  3. goody1zain
  4. goodyzain1
  5. goodyzain19
  6. 1goodyzain9

...etc

The user can have max of two integer numbers b/w 0-9 in the name...i tried following regex...

(?:\d{0,2}+[a-zA-Z]|[a-zA-Z]+\d{0,2})|[a-zA-Z]

works fine for case 1,4,5 but fails for others....a help will be appreciable...:)

Upvotes: 1

Views: 57

Answers (3)

Barmar
Barmar

Reputation: 780818

Try this:

^(?:[a-zA-Z]*\d){0,2}[a-zA-Z]*$

Upvotes: 1

kitensei
kitensei

Reputation: 2530

Try using the negative pattern:

$output = preg_replace( '/[^0-9]/', '', $string );

and then count the $output length, if you have >2 then it's a wrong format

if (2 > preg_replace('/[^0-9]/', '', $string)) {
    // ok
} else {
    // not ok, more than 2 digits
}

Upvotes: 1

vks
vks

Reputation: 67968

(?!([a-zA-Z]*?\d){3,})^[a-zA-Z\d]+$

This works.See demo.Uses a negative lookahead.

http://regex101.com/r/iX5xR2/7

Upvotes: 0

Related Questions