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))
. None of them is working. Any ideas?
The () will allow you to read exactly which characters were matched. Parenthesis are also useful for OR'ing two expressions with the bar | character. For example, (a-z|0-9) will match one character -- any of the lowercase alpha or digit.
Square brackets ( “[ ]” ): Any expression within square brackets [ ] is a character set; if any one of the characters matches the search string, the regex will pass the test return true.
Python Regex Escape Parentheses () You can get rid of the special meaning of parentheses by using the backslash prefix: \( and \) . This way, you can match the parentheses characters in a given string.
In standard expression syntax, parentheses and intervals have distinct meanings. How can you tell a regex that you want it to fit real parentheses and periods? Ans: Periods and parentheses can be escaped with a backslash: \., \(, and \).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With