tags:

views:

53

answers:

2

I need to extract a substring from a formatted value as follows:

“(The original reference for ‘item1’ is: 12345)”

The text that I need is 12345. ‘item1’ can change, although the rest of the string should remain static.

I currently have something like this:

  string myString = “(The original reference for ‘item1’ is: 12345)”;
  string regexMatch = "(The original reference for .* is: ";
  Regex regex = new Regex(regexMatch);
  Console.WriteLine(regex.Match(myString).ToString());

This just errors saying I need a closing bracket. Can someone point me in the right direction on this one, please?

+2  A: 

You need to escape the (.

string regexMatch = @"\(The original reference for .* is: ";

Note that @ sign, which causes the compiler to not process escape sequences in the string.
Otherwise, you would need to escape the \ itself from the compiler, like this: "\\(...".

Also, you probably want a lazy wildcard:

string regexMatch = @"\(The original reference for .*? is: ";
SLaks
+1  A: 

You want the number in this textual context, right? So try this regex:

string regexMatch = @"(?<=\(The original reference for '[^']+' is: *)\d+(?=\))";

The value of the match will then be the number (nothing else).

Lucero