Tom
Tom

Reputation: 75

Number followed by any amount of [comma][number]

Matching strings of unknown length - I'm taking an input from a user from a form.
The intended input is in the format [number][comma][number][comma] etc...
An example of this input would be 3,43,1,238,24.

The pattern can continue as long as the input allows, and any length number is accepted.

I'd like to use a regular expression to ensure that the user has formatted their entry correctly. First, I used str_replace to strip out any spaces within the response (just in case the user input spaces after the commas).

But I'm confused about how to match a pattern of unknown length. Would the following work?

/\d+,\d+/

I'm under the impression that this wouldn't work. It would only match the first two numbers in the pattern, and nothing after it. Any ideas?

If it matters, I'm using PHP v 5.6.10

Upvotes: 1

Views: 88

Answers (2)

Fernando Nunes
Fernando Nunes

Reputation: 29

You can use this pattern: /(\d+)[^,]?+/gm

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

As PHP PCRE doesn't have the global (g) modifier, you should remove it and use preg_match_all().

Example:

$str = '55, 44, 23 , 65 , 99,
234, 5 34,';

preg_match_all('/(\d+)[^,]?+/', $str, $matches);

print_r($matches);

Hope it helps!

Upvotes: -1

melpomene
melpomene

Reputation: 85827

You'd use something like /^\d+(?:,\d+)*$/. This means:

^      # beginning of string
\d+    # one or more digits
(?:    # group (but don't capture)
  ,    #   a comma
  \d+  #   one or more digits
)*     # ... zero or more of this group
$      # end of string

This treats an input like 3,43,1,238,24 as a "head" (3) followed by (arbitrarily many) comma-number pairs (,43 ,1 ,238 ,24).

Upvotes: 4

Related Questions