Home > other >  I want to check string using regex | not nested, stuck together and must have content
I want to check string using regex | not nested, stuck together and must have content

Time:10-13

I have some strings.

  1. [ABC]
  2. [ABC][DEF]
  3. [ABC][def][GH][I] and etc.

and there are rules.

  1. Do not nested.
  • [ABC] : OK
  • [A[BC]] : NO
  1. Not allowed any character between each brackets. (includes white spaces)
  • [ABC][DE] : OK
  • [AB] [C] : NO
  • [AB]c[DEF] : NO
  1. String must start with "[" and end with "]"
  2. 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 ]) $
  • Related