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...

3
  • 2
    why not Regex.Split(input,"test-string") Commented Oct 29, 2013 at 11:20
  • 1
    There's nothing built-in in the framework, but someone already implemented an algorithm to do that: stackoverflow.com/a/1731641/87698 Commented Oct 29, 2013 at 14:59
  • possible duplicate of Parsing formatted string Commented Oct 29, 2013 at 15:06

2 Answers 2

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"]);
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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},...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.