问题描述
首先介绍一下背景.我有类似于以下内容的字符串:
First, a little background. I have strings that resemble the following:
((Foo.Bar.StartsWith("A")) &&(Foo.Bar.EndsWith("B")))
我正在尝试将它们重新格式化为如下所示:
And I'm trying to reformat these to look like this:
((Foo.Any(Bar.StartsWith("A"))) &&(Foo.Any(Bar.EndsWith("B"))))
旁注:.Bar 后面的部分有时可能不包含 (),例如 .Bar == "AB" .
Side Note: The parts following the .Bar may sometimes not include (), like .Bar == "AB" .
我试图捕获两个群体:Foo.和 Bar.StartsWith("") .我计算出了以下模式,但它去掉了尾随括号.
I'm trying to capture two groups: the Foo. and the Bar.StartsWith("<A or B>") . I worked out the following pattern but it drops the trailing parenthesis.
\((Foo\.)(.*?)\)
因此,我得到的不是我想要的,而是:
So instead of getting what I'm looking for, I'm getting:
((Foo.Any(Bar.StartsWith("A")) &&(Foo.Any(Bar.EndsWith("B")))
短的是两个括号.
问题是我需要在 .* 中包含右括号吗?匹配 IF 那里还有一个左括号.我还没想好怎么做,有人知道吗?
The problem is I need to include closing parentheses in the .*? match IF there's also an opening parenthesis in there. I haven't figured out how to do this, anyone know?
PS - 代码是 C#.NET,但这应该无关紧要,除非解决方案涉及一些晦涩难懂的特定于语言的 RegEx 内容.
PS - The code is C#.NET but that shouldn't matter unless the solution involves some obscure language-specific RegEx stuff.
推荐答案
您是否有理由必须使用正则表达式执行此操作?试图找到匹配"对是正则表达式做得不好的事情之一.
Is there a reason you have to do this with regular expressions? Trying to find "matching" pairs is one of the things that regex does not do well.
我会通过普通代码来完成.进行搜索以找到 "(Foo."
,然后进行一个循环,迭代后续字符,保留一个计数器,记录您传递了多少开/关括号.当您点击 (
并在您点击 时递减)
.如果您点击一个右括号并且计数器为 0,那就是您需要捕获的字符串的末尾.停止捕获点,把那个字符串放在你要添加的 Any()
中.然后找到下一个 "(Foo."
.
I would just do it through normal code. Do a search to find "(Foo."
, then make a loop that iterates over the subsequent characters, keeping a counter for how many open/close parentheses you have passed. Increment it when you hit a (
and decrement when you hit a )
. If you hit a closing parenthesis and the counter is at 0, that's the end of the string you need to capture. Stop capturing at that point, take that string and put it inside your Any()
that you're adding. Then find the next "(Foo."
.
有意义吗?如果您没有真正遵循我的意思,我可能可以对它进行伪代码.当然,如果您无论如何都可以放弃正则表达式,这只是一个有效的选择.
Does that make sense? I could probably pseudocode it if you're not really following what I mean. Of course, this is only a valid option if you're able to abandon regular expressions anyway.
这篇关于匹配正则表达式中的开始/结束对字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!