0

Possible Duplicate:
Regular Expression to match outer brackets

I'm trying to match a string that contains parentheses but escaping the parentheses with a backslash gives me an error "unrecognized escape sequence". How do i match the parenthesis and retrieve whats inside?

Community
  • 1
  • 1
Max
  • 59
  • 2
  • 7
  • You cannot match *balanced* parenthesis with a regexp (which is a finite state automaton, but balancing parenthesis requires more, e.g. a stack or counting automaton which have an infinite set of states). – Basile Starynkevitch Oct 02 '12 at 06:38
  • You should be able to escape parentheses with a backslash, perhaps you could provide us with some code that you have tried? – Eyvind Oct 02 '12 at 06:40
  • all i need is a simple "text text text (stuff i need to get) text text" it doesnt need to have nested parenthesis or anything i just cant figure out how to get it to match one single parentheses character without giving me the unrecognized escape sequence error – Max Oct 02 '12 at 06:41
  • the code ive tried looks pretty much like this: "\((\"([^\"]+)\")\)". The backslash escapes the double quote fine but it doesnt work when i try to put a backslash in front of the parenthesis – Max Oct 02 '12 at 06:43
  • @BasileStarynkevitch: Actually, .NET regexes can match balanced parentheses correctly, using `(?)` and `(?)` counters. – Tim Pietzcker Oct 02 '12 at 06:43

1 Answers1

0

use Regex.Escape(): http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx

  • How would i go about distinguishing between the parenthesis i expect in the string and the parenthesis that are telling the regex what I want to return from the string? – Max Oct 02 '12 at 07:01
  • something like string pattern = Regex.Escape("[") + "(.*?)]"; you can get more from the link i provided. –  Oct 02 '12 at 08:35