0

I'm currently working with a piece of code in c#/Asp.net.

It uses a regex replace function structured like this:

return regex.Replace(pattern, match =>
{
    // do something
    return something;
});

An example pattern might be "This is a {sample} bit of text where the items in the brackets are {replaced}"

This form of replace syntax seems to be all or nothing — it gets all matches and will replace all matches with something.

Here's the full code which was posted by Mark Gravell:

How can I create a more user-friendly string.format syntax?

However, I need to be able to conditionally replace — get matches, iterate through them, and decide to replace or not.

Example

Given the input string:

"You are {age} years old and your first name is {firstName} and yourlast name is {lastName}.

Usage

string s = Format("You are {age} years old and your first name is {firstName} and yourlast name is {lastName}.", new {age = 18, firstName = "Foo"});

Current output

"You are 18 years old and your first name is Foo and yourlast name is ."

Desired output

"You are 18 years old and your first name is Foo and yourlast name is {lastName}."

Any advice appreciated.

9
  • 4
    Please make your question concrete: what text have you got and what do you need to get in the end? The snippet above looks like a sample code from the docs, what have you tried? What is your problem? Commented Nov 6, 2017 at 10:29
  • @WiktorStribiżew - I recently posted the question in a lot more detail and got slayed for a lack of clarity. I am writing an extension that will replace the properties in the brackets with properties I supply - like string.format. The above code will replace all and there is no option to opt out. I wan't to be able to find matches then choose to replace. I don't need extensive code, just an idea as to how to separate out the replace and match functionality. Commented Nov 6, 2017 at 10:39
  • In the code I linked to, just use var pattern = @"(?<={).*?(?=})"; for it work with no other changes in the further code. Certainly, you may enhance it by using @"{(.*?)}" or @"{([^{}]*)}" pattern and then using m => $"{{{variablesDictionary[m.Groups[1].Value]}}}". Commented Nov 6, 2017 at 10:40
  • Also, see this demo. Commented Nov 6, 2017 at 10:45
  • 1
    @WiktorStribiżew - using the match.value worked - thanks for that. Commented Nov 6, 2017 at 11:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.