1

I have the following Regex that is being used to matching incoming packets:

public static class ProtobufConstants
{
    public static Regex ContentTypeNameRegex => new Regex("application/protobuf; proto=(.*?)");
}

I also need to write outgoing packets strings in the same format, i.e. create strings similar to "application/protobuf; proto=mynamespace.class1" ideally by using the same regex definition new Regex("application/protobuf; proto=(.*?)");.

To keep this code in one place, is it possible to use this regex template and replace the (.*?) parameter with a string (as per above example i would like to substitute "mynamespace.class1").

I see there is a Regex.Replace(string input, string replacement) but given the above ContentTypeNameRegex already has the format defined I don't have an input per se, I just want to format - not sure what to put here, if anything.

Is it possible to use in this manner, or do i need to revert to string.Format?

4
  • public static Regex ContentTypeNameRegex(string protoPattern = ".*?")? Commented Oct 13, 2018 at 20:43
  • Hi Ahmed thanks for the quick reply, have updated my question as may not have been clear Commented Oct 13, 2018 at 20:55
  • Check the updated answer below. Commented Oct 13, 2018 at 21:02
  • Regex is really not for formatting without an input. Commented Oct 13, 2018 at 21:58

2 Answers 2

2

If you just want to replace the matched group with something else, you can change your pattern to:

(application/protobuf; proto=)(.*?)

That way, you can replace it by doing something like:

Regex re = ContentTypeNameRegex;
string replacement = "mynamespace.class1";
re.Replace(input, "$1" + replacement);
Sign up to request clarification or add additional context in comments.

Comments

0

Use Regex.Replace but use the match evaluator to handle your formatting needs. Here is an example which simply replaces a slash with a dash and visa versa, based on what has been matched.

var text = "001-34/323";

Regex.Replace(text, "[-/]", me => { return me.Value == "-" ? "/" : "-";   })

Result

001/34-323

You can do the same with your input, to decide to change it or send it on as is.

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.