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?
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: ";
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.