简体   繁体   中英

Need to replace a string C#

I need to replace:

string input = "%someAlphabets%.ZIP"
string replaceWith = "Hello"
string result = "Hello.ZIP"

I tried with Regex.Replace(inputString,"[%][A-Za-z][%]", replacedWith); but it is not working.

The problem in your expression is that, there is only one alphabet in between % signs. You need to repeat the alphabets.

Regex.Replace(inputString,"[%][A-Za-z]{1,}[%]", replacedWith);

Try this:

string input= "%someAlphabets%.ZIP"
string regex = "(%.*%)";
string result = Regex.Replace(input, regex, "Hello");

It doesn't care if the name is alphabet only but that you can change by changing the .* caluse to your selection logic.

As already mentioned in the comments, you don't need RegEx for this.

More simpler alternatives may be:

  1. Using string.Format
string.Format("{0}", input)`
  1. Using string interpolation
var input = "Hello";
var result = $"{input}.zip";
  1. Using string.Replace method
var input = "%pattern%.ZIP"
var with = "Hello"
var result = input.Replace("%pattern%", with);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM