2

Edit: Solution by @Heinzi https://stackoverflow.com/a/1731641/87698


I got two strings, for example someText-test-stringSomeMoreText? and some kind of pattern string like this one {0}test-string{1}?.

I'm trying to extract the substrings from the first string that match the position of the placeholders in the second string.

The resulting substrings should be: someText- and SomeMoreText.

I tried to extract with Regex.Split("someText-test-stringSomeMoreText?", "[.]*test-string[.]*\?". However this doesn't work.

I hope somebody has another idea...

Community
  • 1
  • 1
Matthias
  • 280
  • 2
  • 9
  • 19

2 Answers2

0

One option you have is to use named groups:

(?<prefix>.*)test-string(?<suffix>.*)\?

This will return 2 groups containing the wanted prefix and the suffix.

var match = Regex.Match("someText-test-stringSomeMoreText?", 
    @"(?<prefix>.*)test-string(?<suffix>.*)\?");
Console.WriteLine(match.Groups["prefix"]);
Console.WriteLine(match.Groups["suffix"]);
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
  • The problem is, those two input strings are completely variable. The second string could also look like `{0}test{1}stringSome{2}Text?` for example. The problem is, I'm looking for a way to create a working regex pattern from this pseudo pattern string dynamicaly. – Matthias Oct 29 '13 at 11:44
0

I got a solution, at least its a bit dynamical.

First I split up the pattern string {0}test-string{1}? with string[] patternElements = Regex.Split(inputPattern, @"(\\\{[a-zA-Z0-9]*\})");

Then I spit up the input string someText-test-stringSomeMoreText? with string[] inputElements = inputString.Split(patternElements, StringSplitOptions.RemoveEmptyEntries);

Now the inputElements are the text pieces corresponding to the placeholders {0},{1},...

Matthias
  • 280
  • 2
  • 9
  • 19