简体   繁体   English

C#正则表达可能被引号括起来的单词

[英]C# Regex for a word possibly surrounded by quotes

For a C# program I'm writing, I'm using regular expressions to look for a specific pattern and this pattern may or may not be surrounded by parentheses, but, if it is, I want to include them in the match. 对于我正在编写的C#程序,我使用正则表达式来查找特定模式,这个模式可能会或可能不会被括号括起来,但是,如果是,我想将它们包含在匹配中。

So for example, say my pattern was just the word "hello" , I created this regex: 例如,假设我的模式只是单词"hello" ,我创建了这个正则表达式:

"\(?hello\)?"

But that doesn't take into account that the word must have BOTH opening and closing parentheses in order to qualify as a match. 但是,这并没有考虑到这个词必须有两个开括号和右括号才能符合条件。 So, for example, if my search string was: 因此,例如,如果我的搜索字符串是:

hello, (hello), (hello, my name is bob), (bob said hello)

What I would want would be to have the following 4 matches - hello , (hello) hello , hello 我想要的是拥有以下4场比赛 - hello(hello) hellohello

Specifically, the second match includes the parentheses, but the 3rd and 4th matches do not include any parentheses since they are not at the beginning AND the ending of the "hello". 具体来说,第二个匹配包括括号,但第3和第4个匹配不包括任何括号,因为它们不在“hello”的开头和结尾。

What kind of regex could I use to accomplish this? 我可以使用什么样的正则表达式来实现这一目标?

You could simply use an alternation to match \\(hello\\) or hello : 您可以简单地使用替换匹配\\(hello\\)hello

\(hello\)|hello

Since regular expressions are inherently greedy, (hello) will be match before hello which means that all four of the instances would be matched. 由于正则表达式本质上是贪婪的, (hello)将在hello之前匹配,这意味着所有四个实例都将匹配。

Before anyone else spends too much time on this, I did find an answer (but if you have a better way, please do share!!!) 在其他人花费太多时间之前,我确实找到了答案(但如果你有更好的方法,请分享!)

After some research, my final pattern has become: 经过一番研究,我的最终模式已成为:

(\()?hello(?(1)\))

That uses an optional capturing group and conditional backreferencing 它使用可选的捕获组和条件反向引用

Again, if anyone has a nicer solution, please do share, but, otherwise, hope this manages to help someone else in the future! 再说一次,如果有人有更好的解决方案,请分享,但是,否则,希望这可以帮助将来的其他人!

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

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