tags:

views:

201

answers:

4

Hello,

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 ried (.)/s((/d+)) and (.) (\d+) and (.*)/s((/d/d/d/d)). None of them is working. Any ideas?

Thank you.

Thank you. NLV

+5  A: 

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.

Diadistis
+1, `(.*) \((\d{4})\)`
Rubens Farias
Took me while to figure out that the second `\ ` is necessary to escape the regex escape character `\ `. I always write my regular expression in verbatim strings: `@"\((.*?)\"` I find it easier to read.
SealedSun
Or `Regex RegexObj = new Regex(@"\((.*?)\)");`.
CannibalSmith
+1  A: 

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

Parrots
A: 

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

Brian Kim
+1  A: 

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.

Gregg
No need to escape the `)` inside a character class.
Bart Kiers