Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parenthesis in Regular Expressions pattern

Tags:

c#

regex

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?

like image 837
NLV Avatar asked Jan 14 '10 18:01

NLV


People also ask

What is () in regular expression?

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.

What do the [] brackets mean in regular expressions?

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.

How do I get out of parentheses in regex?

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.

How can you tell a regex that you want it to fit real parentheses and periods?

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 \).


1 Answers

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.

like image 78
Diadistis Avatar answered Sep 28 '22 00:09

Diadistis