I have some strings.
- [ABC]
- [ABC][DEF]
- [ABC][def][GH][I] and etc.
and there are rules.
- Do not nested.
- [ABC] : OK
- [A[BC]] : NO
- Not allowed any character between each brackets. (includes white spaces)
- [ABC][DE] : OK
- [AB] [C] : NO
- [AB]c[DEF] : NO
- String must start with "[" and end with "]"
- Bracket content can have word and number only. not empty or blank.
Here is my works. But it seems not good.
^\[\w.*(\w\]\[\w).*\w\]$
https://regex101.com/r/EQzulB/1
How do I check if this string is valid or invalid?
CodePudding user response:
The ^\[\w.*(\w\]\[\w).*\w\]$
regex matches the start of string (^
), then [
, a word char, any zero or more chars other than line break chars as many as possible, then a word char, ][
and a word char captured into Group 1, then again any zero or more chars other than line break chars as many as possible and a word char followed by a ]
char at the end of string ($
). So, [ABC]
and [A[BC]]
can't match, there is no w][w
in it.
You can use
^(?:\[[a-zA-Z0-9] ]) $
See the regex demo. Details:
^
- start of string(?:\[[a-zA-Z0-9] ])
- one or more occurrences of\[
- a[
char[a-zA-Z0-9]
- one or more alphanumeric chars]
- a]
char
$
- end of string.
If you allow underscores, too, inside the square brackets, use \w
:
^(?:\[\w ]) $