- Home /
Question by
theUndeadEmo · Sep 23, 2016 at 10:23 AM ·
c#stringregex
How to replace a word inside a string with different white space combos?
Hi, i have got this scenario where there can be number of spaces in between POWER=? (ie. POWER=..............?, POWER........=............?,POWER................. =?). or in some cases POWER=? does not exist.
I want to just replace the ? where there is the word POWER=, with a number. and put it in a format without spaces example POWER...=........................?, turns into POWER=1000,
i know i have to use regex but i cant find anything helpful to deal with this.
please find below the list of scenarios
int POWER = 9001;
string[] combinations = { "SPEED = 100, POWER =?, Item=#21212",
"SPEED = ?, Item=#21212",
"SPEED = 100, POWER=?, Item=#21212",
"SPEED = 100, POWER = ?, Item=?",
"POWER =?, SPEED = 100, Item=#21212"
};
for (int i = 0; i < combinations.Length; i++)
{
if (combinations[i].Contains("POWER=?"))
{
string newStr = combinations[i].Replace("POWER=?", "POWER=" + POWER);
combinations[i] = newStr;
}
}
Comment
I am not good with regular expressions but this works:
string pattern =@"(.*POWER\s*=\s*)\?(\s*.*)";
for (int i = 0; i < combinations.Length; i++)
{
string newStr = combinations[i];
combinations[i] = System.Text.RegularExpressions.Regex.Replace(newStr,pattern, m => m.Groups[1].Value + POWER + m.Groups[2].Value);
}