-1

I have a regex, which is: /[0-9]+(,[0-9]+)*/.

It accepts only numbers, separated by a comma. For instance:

1,2,3,4 = good
,1,2,3,4 = bad
1,2,3,4, = bad
String = bad

But it also accepts a numbers with a space:

1, 2, 3, 4 = good

How to make regex that wouldn't allow to do so and would only let to enter a numbers, separated by a comma without spaces?

Mohammad
  • 21,175
  • 15
  • 55
  • 84
HELPME
  • 714
  • 14
  • 35
  • You may try this `[\d](,[\d\S])*` where `\S` means not white space. I've removed the `+` because would validate for `123,2,34,345` too – enxaneta Sep 29 '18 at 13:16
  • 1
    @enxaneta That would allow any non whitespace character. `µ`, `!`, `a`, etc. – user3783243 Sep 29 '18 at 13:42

3 Answers3

1

This should work:

/^\d(,\d)*$/
  • ^ match the beginning of the string
  • \d match a digit
  • $ match the end of the string

Example:

if (preg_match("/^\d(,\d)*$/", $string))
    echo "good";
else
    echo "bad";
mozkomor05
  • 1,367
  • 11
  • 21
0

Use this:

^(\d,(?=\d))*\d$

How it works:

  • ^: match strings which starts with..(what follows)
  • (...)*: what inside the brackets can be repeated any number of times
  • \d,(?=\d): this is the block that is allowed to repeat. It looks for a number from 0 to 9 followed by a comma which is followed by a number. The number following the comma is not included in the match.
  • \d$: finally, the string must terminate with a number.
Neb
  • 2,270
  • 1
  • 12
  • 22
0

Your regex is correct as is, you just need to use anchors so you check the full string, and not a partial match.

^[0-9]+(,[0-9]+)*$

https://regex101.com/r/zU22VX/1/

An alternative approach could be:

$string = '1,2,3,4';
$array = str_getcsv($string);
foreach($array as $number) {
    if(!is_numeric($number)) {
        echo 'Bad value' . $number;
        break;
    }
}
user3783243
  • 5,368
  • 5
  • 22
  • 41