简体   繁体   English

无法匹配正则表达式组中的括号

[英]Cannot match parentheses in regex group

This is a regular expression, evaluated in .NET 这是一个正则表达式,在.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 GUID
  • newguid() newguid()

The pattern I am using is the following: 我使用的模式如下:

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

But this doesn't match the parentheses, I am getting only the following matches: 但这与括号不匹配,我只得到以下匹配:

  • guid GUID
  • newguid 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). 您的正则表达式- ([^(?<=\\${)(.*?)(?=})->]+) -匹配除负字符类中定义的字符以外的1+个字符(即1个或多个)除(?<等)以外的其他字符。

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] . 您需要的结果在match.Groups[1]match.Groups[2]

Pattern details : 图案细节

  • \\${ - match ${ literal character sequence \\${ -匹配${文字字符序列
  • ([^}]*?) - Group 1 capturing 0+ chars other than } as few as possible ([^}]*?) -组1捕获除}以外的0+个字符
  • -> - a literal char sequence -> -> -文字字符序列->
  • ([^}]*) - Group 2 capturing 0+ chars other than } as many as possible ([^}]*) -组2尽可能捕获除}以外的0+个字符
  • } - 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 . 参见regex演示 However, it is much less generic. 但是,它的通用性要差得多。

Your input structure is always ${identifier->identifier()} ? 您的输入结构始终是${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() . 否则,您可以将regexpr修改为([^?<=\\${.*??=}\\->]+) :使用此rexexpr,您应该匹配输入并获得所需的组: uidnewguid() 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. 关键变化是引用-炭,这是intendend为运营商范围内无报价和力量你在模式中插入括号-但是...... [^......(....)....]从比赛中排除括号。

I hope than can help! 希望能有所帮助!

EDIT: testing with https://regex101.com helped me a lot... showing me that - was intended as range operator. 编辑:使用https://regex101.com进行的测试对我很有帮助...向我展示了-用作范围运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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