简体   繁体   中英

How to extract text that lies between parentheses

I have string like (CAT,A)(DOG,C)(MOUSE,D)

i want to get the DOG value C using Regular expression.

i tried following

Match match = Regex.Match(rspData, @"\(DOG,*?\)");
if (match.Success)
 Console.WriteLine(match.Value);

But not working could any one help me to solve this issue.

You can use

(?<=\(DOG,)\w+(?=\))?
(?<=\(DOG,)[^()]*(?=\))

See the regex demo .

Details :

  • (?<=\(DOG,) - a positive lookbehind that matches a location that is immediately preceded with (DOG, string
  • \w+ - one or more letters, digits, connector punctuation
  • [^()]* - zero or more chars other than ( and )
  • (?=\)) - a positive lookahead that matches a location that is immediately followed with ) .

As an alternative you can also use a capture group:

\(DOG,([^()]*)\)

Explanation

  • \(DOG, Match (DOG,
  • ([^()]*) Capture group 1, match 0+ chars other than ( or )
  • \) Match )

Regex demo | C# demo

String rspData = "(CAT,A)(DOG,C)(MOUSE,D)";
Match match = Regex.Match(rspData, @"\(DOG,([^()]*)\)");
if (match.Success)
    Console.WriteLine(match.Groups[1].Value);
}

Output

 C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM