'Regex to match multiple cases
I have the following examples that must match with my regex
1,[]
1,[0,0,0,[]]
1,[0,0,0,0,0,[]]
1,1
1
I came up with a simple way of matching the middle ones with .?,\[.*\[\]\]
but it doesnt match the first and the last one.
Maybe this is too much to handle with regex but I want to check the following things:
- If there is a ',' it should have a following character or characters(numbers or letters)
- If a bracket is opened: it should close '[]'
- The bracket insides can be whatever but it must respect rule 1 and 2.
I am trying to find a solution so I'm grateful if you can help me. Thank you.
Solution 1:[1]
You can use
^\d+(?:,(?:(\[(?:[^][]++|\g<1>)*])|\d+))?$
See the regex demo. Details:
^
- start of string\d+
- one or more digits(?:,(?:(\[(?:[^][]++|\g<1>)*])|\d+))?
- an optional sequence of,
- a comma(?:(\[(?:[^][]++|\g<1>)*])|\d+)
- one of the alternatives:(\[(?:[^][]++|\g<1>)*])
- Group 1:[
, then zero or more occurrences of one or more chars other than[
and]
or Group 1 pattern recursed|
- or\d+
- one or more digits
$
- end of string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wiktor Stribiżew |