Search code examples
phpregexpreg-match

Conditional regex match based on two non-capturing groups


I've been looking for what seems like hours, and I just cannot find a solution for this. My regex skills are terrible but I'm sure for someone with the knowledge this will be easy.

/^(?:[1-9]{1,3}GB)|(?:[0-9]{1,2}.[0-9]{1,2}TB)$/i

As you can see it's pretty simple. I just need to match one or the other but I don't know where I'm going wrong.

Examples:

<?= $validate->data('100GB'); ?>

This should match since it's 3 digits followed by "GB."

<?= $validate->data('2.65TB'); ?>

This should also match since it's 1 digit followed by period, followed by two more digits, followed by "TB."

EDIT: I needed to modify the numeric count but still doesn't perform as expected.

For anyone interested, here is the final regex.

/^(?:[0-9]{1,3}(?:GB|TB))|(?:[0-9]{1,2}\.[0-9]{1,2}(?:GB|TB))$/i

Solution

  • You are not including zeros in your regex, that is why the pattern fails.

    [1-9]{3} will only match three digits 1-9. So 111 is a match. 234 is also a match.
    But 500 is not.

    With this regex: ([0-9]{3}GB)|([0-9]{1,2}.[0-9]{1,2}TB) you will be able to catch the zeros and it will not limit you to two digit TB disks.

    https://regex101.com/r/6undez/3

    EDIT: In case you want to match 100 GB note the space. You can use this regex:
    https://regex101.com/r/6undez/4
    ([0-9]{3}\s?GB)|([0-9]{1,2}.[0-9]{1,2}\s?TB)