0

I need to match following pattern using php Regular expression but it doesn't give expected out come.

ex:- need to match pattern 5555 5545 9930

$id = "4567 3423 4567";
$regex = "/^[1-9]\d{4} \d{4} \d{4}$/";
if (preg_match($regex, $id)) {
   // Indeed, the expression "^[2-9]\d{2} \d{3} \d{4}$" matches the date string
   echo "Found a match!";
}else {
   // If preg_match() returns false, then the regex does not
   // match the string
   echo "The regex pattern does not match. :(";
}
4
  • 1
    You're a digit short on the first two sections. Commented Sep 14, 2016 at 11:06
  • 1
    Try "/^[2-9]\d{2,3} \d{3,4} \d{4}$/" or - if you do not want to match mixed input types - "/^(?:[2-9]\d{2} \d{3}|\d{4} \d{4}) \d{4}$/" Commented Sep 14, 2016 at 11:07
  • Any feedback? You actually did not mention if you need to support both string formats, or just re-vamp the existing one into a different pattern. Commented Sep 14, 2016 at 11:42
  • it always goes to "The regex pattern does not match." Commented Sep 15, 2016 at 8:42

3 Answers 3

1

If you want to match: 4 non-zero digits + space + 4 digits + space + 4 digits

^([1-9]){4} \d{4} \d{4}$ should do the trick

Sign up to request clarification or add additional context in comments.

Comments

1

I think the safest way to modify the existing regex is by adding an alternative to the first [2-9]\d{2} \d{3}:

^(?:[2-9]\d{2} \d{3}|\d{4} \d{4}) \d{4}$
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

See the regex demo

Details:

  • ^ - start of string
  • (?:[2-9]\d{2} \d{3}|\d{4} \d{4}) - one of the alternatives:
    • [2-9]\d{2} \d{3} - a digit from 2 to 9, any 2 digits, a space and 3 digits
    • | - or
    • \d{4} \d{4} - 4 digits, space, 4 digits (for the new string types)
  • - a space
  • \d{4} - 4 digits
  • $ - end of string.

See the PHP demo:

$id = "4567 3423 4567";
$regex = "/^(?:[2-9]\d{2} \d{3}|\d{4} \d{4}) \d{4}$/";
if (preg_match($regex, $id)) {
    echo "Found a match!";
} else {
    echo "The regex pattern does not match. :(";
}

1 Comment

Did it finally work for you? Do you need more assistance with this task?
0

Simple edit of your regular expression will be

^[1-9]\d{3} \d{4} \d{4}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.