Not able to match regex

63 views Asked by At

I have a string like "5-2,5-12,15-27,5-22,50-3,5-100"

I need a regular expression which matches all the occurrences like below: -

5-2
5-12
5-22
5-100

What will be the correct regex that matches all of them.

3

There are 3 answers

0
Rahul On BEST ANSWER

Use below regex:

(?<!\d)5-\d{1,}

DEMO

0
Toto On

Not sure to well understand your needs, but, how about:

$str = "5-2,5-12,15-27,5-22,50-3,5-100";
preg_match_all('/\b5-\d+/', $str, $matches);
print_r($matches)

or

preg_match_all('/\b\d-\d+/', $str, $matches);

Output:

Array
(
    [0] => Array
        (
            [0] => 5-2
            [1] => 5-12
            [2] => 5-22
            [3] => 5-100
        )

)
0
Dalorzo On

How about:

Online Demo

/(?<!\d)\d\-\d{1,3}/g

If understand correctly the first part of the pattern is one single digit \d therefore we need to exclude other number with a lookbehind (?<!\d) followed by a - and last seems to be a number up to 3 digits if you need more you can remove the 3 and it will also work so it is either \d{1,3} or \d{1,}