I need to validate a string for given specifications:
const string = 'd(iig(i)), d(iitm), d' // is valid
Mainly the string represents one or multiple blocks of d
, which can be without brackets or empty brackets.
Each block is separated by comma and an optional space.
Inside of this block there can be g, i, t or m. Only g can optionaly open new bracket.
I started with this regex:
if (!/^[dgitm, ()]*$/.test(string)) {
throw Error('Pattern has invalid character')
}
But I don't know how to treat these specifications:
- Each block has to be separated by a comma (optinal with space)
- Space is only allowed (optional) between d-blocks
- d and g could have following brackets; i, t and m should not have following brackets
- d is never inside any bracket
Valid
dd(ii)
d(i),d(g)
d(g(iig))
d(g(iig(i)))
Invalid
d(g(d)) // no nested d
d(x) // invalid character
d(i()) // no brackets for i (only d or g)
d(ii)d(ii) // missing comma
i // missing first level d
Update
Removed the spec for balanced brackets, as this can't be tested by regEx.