Sandra S.
Sandra S.

Reputation: 181

C# Replace expression matching start end

Can anyone help me do a replace in a string in C# of any any string starting with "startingChars" and ending with "endingChars"...something like that:

Regex.Replace(strToReplaceIn, "startingChars[anyNumberOfChars]endingChars", myFunction(anyNumberofChars));

where strStartingChars and strEndingChars are two strings and myFunction is defined

for example, if a starting is "Hello, I need to replace startingCharsWITH_SOMETHINGendingChars, ...." the result to be: "Hello, I need to replace myFunctionResult("WITH_SOMETHING"), ..."

Please, let me know the Regex.Replace expression that will help, the problem is not finding the matching expression, but the replacing...how can I refer to

anyNumberOfChars  

in the replacement parameter of the expression?

I hope it's clear enough...Thank you

Upvotes: 0

Views: 2107

Answers (3)

Paolo Tedesco
Paolo Tedesco

Reputation: 57202

You can use a named group to easily get the contents to replace, and a match evaluator to construct the replacement string:

using System.Text.RegularExpressions;

static class Program {
    static void Main(string[] args) {
        string strToReplaceIn = "Hello, I need to replace startingCharsWITH_SOMETHINGendingChars, ....";
        string replaced = Regex.Replace(strToReplaceIn, "startingChars(?<contents>.*?)endingChars", (match) => {
            return "myFunctionResult(" + match.Groups["contents"].Value + ")";
        });
    }
}

A named group (the (?<contents>.*?) bit in the expression) is something that lets you refer to a subpart of the expression, which I think is what you are asking for.
Alternatively, you could use a simple group , i.e. just an expression between parenthesis, without the ?<name> part: (.*). Then, you should refer to it with an integer index:

match.Groups[1].Value

(Note: Groups[0] represents the whole match)

Upvotes: 2

Jacek
Jacek

Reputation: 12053

^yourString&

^ - means start of your string
& - end of your string

Upvotes: 0

davidrac
davidrac

Reputation: 10738

You should use a regexp like that:

abc.*xyz

It'll match strings like that:

abcblablablaxyz

Consider using a minimal match:

abc.*?xyz

This will only match up to the first xyz, instead of searching up to the last one.

Upvotes: 2

Related Questions