I'm using Java's regex library. I want to validate a string against the following format:
31,5,46,7,86(...)
The amount of numbers is not known. I want to make sure there is at least one number in that string, and that every two numbers are separated by a comma. I also want to get the numbers from the string.
(Note: this is just a simplified example, string.split will not solve my actual problem)
I wrote the following regex:
({[0-9]++)((?:,[0-9]++)*+)
The validation part works. However, when I try to extract the numbers, I get 2 groups:
Group1: 31
Group2: ,5,46,7,86
regex101 version: https://regex101.com/r/xJ5oQ6/3
Is there a way I can get each number separately? i.e. to end up with the collection:
[31, 5, 46, 7, 86]
Thanks in advance.
This might work for you:
The above captures one or two digits followed by
,
or end of input.Note that I used the
g
lobal modifier.Try it online
Java does not allow you to access the individual matches of a repeated capturing group. For more information look at this question: Regular Expression - Capturing all repeating groups
The code provided by Tim Pietzcker can help you as well. If you rework it a bit and add a special case for the first number you can use something like this:
This outputs: