A regular expression for receiving text between curly braces that works with random missing curly braces

I have text like

The quick brown [fox] jumps over the lazy [dog]

If I use regex

\[(.*?)\]

I get matches like

fox
dog

I am looking for a regex that works even if one of the curly braces is missing.

For example, if I have text like this

The quick brown [fox jumps over the lazy [dog]

I want the matches to return the "dog"

Update: Another example if I have text like this

The quick brown [fox] jumps over the lazy dog]

I want the matches to return the "fox"

The text may contain several matches, and also several curly brackets may be absent: (.

I can also use C # to substring the results obtained from regular expression matches.

+4
3

-, [ ] [ ] , ,

\[([^][]*)]

  • \[ - [
  • ([^][]*) - 1 0+ , [ ] ( [^...] , , ) ( 1 Regex.Match(INPUT_STRING, REGEX_PATTERN).Groups[1].Value)
  • ] - ] ( )

regex #

var list = new List<string>() {"The quick brown [fox] jumps over the lazy dog]",
        "The quick brown [fox] jumps over the lazy [dog]",
        "The quick brown [fox jumps over the lazy [dog]"};
list.ForEach(m =>
             Console.WriteLine("\nMatch: " + 
                Regex.Match(m, @"\[([^][]*)]").Value + // Print the Match.Value
                "\nGroup 1: " + 
                Regex.Match(m, @"\[([^][]*)]").Groups[1].Value)); // Print the Capture Group 1 value

:

Match: [fox]
Group 1: fox

Match: [fox]
Group 1: fox

Match: [dog]
Group 1: dog
+1

: \[[^[]*?\]

, [.

+4

Here you go: \[[^\[]+?\]

It just avoids being captured [by the char class.

+1
source

All Articles