Calin Serban
Calin Serban

Reputation: 21

c# regular expression exclude certain character

I am trying to match a string in C# using Regex.IsMatch that has the following format:

([anything here[anything here]anything here])+

Example: [mark[MARK]mark][[spacing]] would be a valid string, but [[[spacing]spacing] would be an invalid one.

Notice that

"anything here"

string cannot contain

"[" or "]"

, and it also can be empty.

I tried something like@"(\[{1}\w*\[{1}\w*\]{1}\w*\]{1})+", but I don't know how to tell the Regex engine that \w* cannot contain

"[" or "]"

.

Thank you!

Upvotes: 2

Views: 5991

Answers (2)

Niyoko
Niyoko

Reputation: 7662

Use this regex

^(\[[^\[\]]*\[[^\[\]]*\][^\[\]]*\])+$

Regex explanations:

  • ^ Match starts of the string
  • ( Start a group
  • \[ Match starting [
  • [^\[\]]* Match zero or more string that is not [ and is not ]
  • \[ Match [ again
  • [^\[\]]* Match zero or more string that is not [ and is not ]
  • \] Match closing ]
  • [^\[\]]* Match zero or more string that is not [ and is not ] (again)
  • \] Match last ]
  • ) Ending group
  • + Quantifier to matches previous group one or more occurence
  • $ Match ends of the string

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You need to use balancing groups, enclose the whole expression within a non-capturing group, and quantify the group with + (one or more occurrences):

^(?:\[(?>[^][]+|(?<o>)\[|(?<-o>)])*(?(o)(?!))])+$

See the regex demo

Details:

  • ^ - start of string
  • (?: - start of a non-capturing +-quantified group
    • \[ - a [
    • (?>[^][]+|(?<o>)\[|(?<-o>)])* - search for any 1+ chars other than [ and ] or [ (adding it to Group "o" stack) or ] (removing it off the Group "o" stack)
    • (?(o)(?!)) - if group "o" is not empty, fail the match, look for the next paired [...]
    • ]
  • )+ - one or more occurrences of the inner pattern
  • $ - end of string.

Upvotes: 1

Related Questions