开发者

Using parenthesis in Regular Expressions pattern

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?

Update 1

so for the text "afasdfas (2009)"

I tried (.)/s((/d+)) and (.) (\d+) and (.*)/s((/d/d/d/d)). Non开发者_如何学Goe of them is working. Any ideas?


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

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


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


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.


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


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

(PatternInsideParenthesis)

will be like this:

\((PatternInsideParenthesis)\)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜