karma_police
karma_police

Reputation: 352

Regular expression for substring with variable length

I have a lot of strings like:

"1248, 60906068, 4536576, 858687( some text 67, 43, 45)"

And I want to check if the string starts from number and there are brackets in string, in same time I want to get all numbers from the begining to the first bracket. So for this example string result should be like:

[0] => 1248 , [1] => 60906068, [2] => 4536576, [3] => 858687

The point is that in the string after first number at the beginning of the string could be zero additional numbers or one number or even a lot of numbers.

I tried something like that:

 ^(\d+)(?:,\s?(\d+)?)*\([^\)]+\)$

But it takes only first and last number before brackets.

Is it possible to get all these numbers with only one Regular Expression?

Thank you in advance!

Upvotes: 0

Views: 123

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You can use this regex: (\d+)(?:\([^\)]+\))?

All numbers will be captured in Group 1.

See example.

Result:

1248
60906068
4536576
858687

Upvotes: 2

Related Questions