C# 在正则表达式模式中使用括号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2066428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:11:49  来源:igfitidea点击:

Using parenthesis in Regular Expressions pattern

c#regex

提问by NLV

I've a string "This text has some (text inside parenthesis)". So i want to retrieve the text inside the parenthesis using Regular Expressions in C#. But parenthesis is already a reserved character in regular expressions. So how to get it?

我有一个字符串“此文本有一些(括号内的文本)”。所以我想在 C# 中使用正则表达式检索括号内的文本。但是括号已经是正则表达式中的保留字符。那么如何获得呢?

Update 1

更新 1

so for the text "afasdfas (2009)"

所以对于文本“afasdfas (2009)”

I tried (.)/s((/d+))and (.) (\d+)and (.*)/s((/d/d/d/d)). None of them is working. Any ideas?

我试着(.)/s((/d+))(.) (\d+)(.*)/s((/d/d/d/d))。他们都没有工作。有任何想法吗?

采纳答案by Brian Kim

You can either use backslash or Regex.Escape().

您可以使用反斜杠或Regex.Escape()

回答by Diadistis

Like this:

像这样:

// For "This text has some (text inside parenthesis)"
Regex RegexObj = new Regex(@"\(([^\)]*)\)");

// For "afasdfas (2009)"
Regex RegexObj = new Regex(@"\((\d+)\)");

Edit:

编辑:

@SealedSun, CannibalSmith : Changed. I also use @"" but this was c/p from RegexBuddy :P

@SealedSun,食人者史密斯:改变了。我也使用 @"" 但这是来自 RegexBuddy 的 c/p :P

@Gregg : Yes, it is indeed faster, but I prefer to keep it simpler for answering such questions.

@Gregg :是的,它确实更快,但我更喜欢让它更简单地回答此类问题。

回答by Parrots

You can escape the parenthesis using the backslash. C# Reg Expression Cheet Sheet

您可以使用反斜杠转义括号。C# Reg 表达式 Cheet 表

回答by Gregg

For any characters that are "special" for a regular expression, you can just escape them with a backslash "\". So for example:

对于正则表达式的任何“特殊”字符,您可以使用反斜杠“\”将它们转义。例如:

\([^\)]*\)

Would capture "(text inside parenthesis)" in your example string.

将在您的示例字符串中捕获“(括号内的文本)”。

[^\)]*

Should be slightly safer than just "." within the parenthesis, and should also be faster.

应该比“.”稍微安全一些。在括号内,也应该更快。

回答by Sara

Just add \(, \)around your Parenthesis. for example:

只需在括号周围添加\(, 即可\)。例如:

(PatternInsideParenthesis)

(PatternInsideParenthesis)

will be like this:

将是这样的:

\((PatternInsideParenthesis)\)

\((PatternInsideParenthesis)\)