简体   繁体   中英

Capture a string which contains '(' and ')' using regular expression

I would like to capture the whole string which appears after 'Value - ' till 'TestRun' in a group capture using the below expression but it does not consider the literal ')'. How to capture the string till 'TestRun'?

Regular expression:

Value - ([\\\w-:_.*\(\)]+)\s

Text:

Value - F:\TEMP\Radio\5\M\Try_Remove\6( alt )\TestRun End

The pattern that you tried does not match a space and will stop matching after the opening parenthesis.

You could for example match what is allowed in the character class without the parenthesis or match from an opening will closing parenthesis using a non capturing group and a quantifier.

Value - ([\\\w:_.*-]+(?:\([^()]*\)[\\\w:_.*-]*)*)\s

Explanation

  • Value - Match literally
  • ( Capture group 1
    • [\\\w:_.*-]+ Match 1+ times any of the listed
    • (?: Non capture group
      • \([^()]*\)[\\\w:_.*-]* Match from ( .. ) and 0+ times any of the listed
    • )* Close group and repeat 0+ times
  • ) Close group 1
  • \s Match a whitespace char

Regex demo (Click the Table tab to see the group value)

A more broad pattern is to match until the last occurrence of the / and then match a following non whitespace chars

Value - (.*\\\S+)\s

Regex demo

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