Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match one or two of a subpattern in a regular expression [duplicate]

I am trying to make a regex to match a certain criteria and I cannot get it working how I want it to.

My current regex is

'/S(?:[0-9]){2}E(?:[0-9]){2}/i'

What I would like it to do is match the following criteria

An S

At least one digit 0-9

An optional digit that can be 0-9

An E

At least one digit 0-9

An optional digit that can be 0-9

I would also like it to match the double numbers over single ones if this is possible, I made up the regex by following tutorials on the internet but think I am missing something.

like image 954
Griff Avatar asked Jan 27 '26 10:01

Griff


1 Answers

Try this:

<?php

$reg = "#S\d{1,2}E\d{1,2}#";

$tests = array('S11E22', 'S1E2', 'S11E2', 'S1E22', 'S111E222', 'S111E', 'SE', 'S0E0');

foreach ($tests as $test) {
    echo "Testing $test... ";
    if (preg_match($reg, $test)) {
        echo "Match!";
    } else {
        echo "No Match";
    } 
    echo "\n";
}

Output:

Testing S11E22... Match!
Testing S1E2... Match!
Testing S11E2... Match!
Testing S1E22... Match!
Testing S111E222... No Match
Testing S111E... No Match
Testing SE... No Match
Testing S0E0... Match!

Explanation:

 $reg = "#S\d{1,2}E\d{1,2}#";
          ^ ^  ^  ^ ^  ^
          | |  |  | |  |
    Match S |  |  | |  One or two times
  Match digit  |  | Match a digit
One or two times  Match the letter E

EDIT

Optionally you could have done this with something like

$reg = '#S\d\d?E\d\d?#';

Which is to say, S followed by digit, possibly followed by another digit ?... so on.

like image 62
sberry Avatar answered Jan 28 '26 23:01

sberry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!