简体   繁体   中英

Cannot match parentheses in regex group

This is a regular expression, evaluated in .NET

I have the following input:

${guid->newguid()}

And I want to produce two matching groups, a character sequence after the ${ and before } , which are split by -> :

  • guid
  • newguid()

The pattern I am using is the following:

([^(?<=\${)(.*?)(?=})->]+)

But this doesn't match the parentheses, I am getting only the following matches:

  • guid
  • newguid

How can I modify the regex so I get the desired groups?

Your regex - ([^(?<=\\${)(.*?)(?=})->]+) - match 1+ characters other than those defined in the negated character class (that is, 1 or more chars other than ( , ? , < , etc).

I suggest using a matching regex like this:

\${([^}]*?)->([^}]*)}

See the regex demo

The results you need are in match.Groups[1] and match.Groups[2] .

Pattern details :

  • \\${ - match ${ literal character sequence
  • ([^}]*?) - Group 1 capturing 0+ chars other than } as few as possible
  • -> - a literal char sequence ->
  • ([^}]*) - Group 2 capturing 0+ chars other than } as many as possible
  • } - a literal } .

If you know that you only have word chars inside, you may simplify the regex to a mere

\${(\w+)->(\w+\(\))}

See the regex demo . However, it is much less generic.

Your input structure is always ${identifier->identifier()} ? If this is the case, you can user ^\\$\\{([^-]+)->([^}]+)\\}$ .

Otherwise, you can modify your regexpr to ([^?<=\\${.*??=}\\->]+) : using this rexexpr you should match input and get the desired groups: uid and newguid() . The key change is the quoting of - char, which is intendend as range operator without quoting and forces you to insert parenthesis in your pattern - but... [^......(....)....] excludes parenthesis from the match.

I hope than can help!

EDIT: testing with https://regex101.com helped me a lot... showing me that - was intended as range operator.

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