tags:

views:

63

answers:

3
    string input = "aaaabbbccc12345677XXXXsfsfsrfsd";
    MessageBox.Show(Regex.Match(input, "7(?<x1>.*)s").Groups["x1"].Value);

That Result


7XXXXsfsfsrf

OK

but i want XXXX Value Only HOW?

   MessageBox.Show(Regex.Match(input, ".*7(?<x1>.*?)s").Groups["x1"].Value);
+1  A: 
"7(?<x1>.*)s"

You need to use the right syntax: Naming a group works like this (?<NameHere>ExpressionHere), see for example here or here.

Benjamin Podszun
+1, but I almost didn't see that; note `<?x1>` was replaced by `?<x1>`
Rubens Farias
Rubens: Yeah, I thought about a way to highlight that in the code (doesn't work as far as I can tell) and forgot to mention it in the text afterwards. Now it should be clear thanks to you. :)
Benjamin Podszun
A: 

You can ask your regex not to be too greedy

"7(?<x1>.*?)s"
Benoit Vidis
A: 

Remember that regular expressions have longest-leftmost semantics. You seem to want the rightmost start with the leftmost end, so that's spelled

MessageBox.Show(Regex.Match(input, "^.*7(?<x1>.*?)s").Groups["x1"].Value);

The subpattern ^.*7 means “starting after the last 7 in the string…” Note that the caret (beginning of string) is redundant, but I like to use it for emphasis with ^.*x meaning the last x.

In contrast, .*? means match as few characters as possible, starting with none.

Greg Bacon