Reputation: 119
This is my first post in this forum. I have text with in double which i want to replace by another text.
This is my full text
"Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor~9999"*"Operational Metrics~Canadian Dollars (Canadian $/US$)~9999"
This text "Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor~9999" will be replace with excel cell address A10.
I have tried this way but not being able to replace the text within double quote. surely there is problem in my code which i am not able to fix.
string mainstr = "\"" + "Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor~9999" + "\"" + "*" + "\"" + "Operational Metrics~Canadian Dollars (Canadian $/US$)~9999" + "\"";
string replacesfrom = "\"" + "Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor~9999" + "\"";
string replacesto = "A10";
string afterreplace = Regex.Replace(mainstr, replacesfrom, replacesto);
Desired output will be.
"A10"*"Operational Metrics~Canadian Dollars (Canadian $/US$)"
I tried this logic too but still no luck.
public static string ReplaceWholeWord(this string original, string wordToFind, string replacement, RegexOptions regexOptions = RegexOptions.None)
{
string pattern = String.Format(@"\b{0}\b", wordToFind);
string ret = Regex.Replace(original, pattern, replacement, regexOptions);
return ret;
}
with above function i try to replace but unfortunately not being able to replace text Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor with A10
Please suggest what to change in my above code.
Upvotes: 0
Views: 133
Reputation: 52
first things first, you don't need the "+" in your strings ecxample:
string replacesfrom = "\"" + "Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor" + "\"";
could be:
string replacesfrom = "\"Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor\"";
And what I could understand, this is what you need, to replace:
string afterreplace = mainstr.Replace(replacesfrom, replacesto)
And to get cell adress, if you don't know how, this should work: How can i get the Cell address from excel
Upvotes: 0
Reputation: 7855
If you desperately want to use Regex, continue reading. If not, see Yaroslav's answer
The problems are that you havenescaped Regex special characters, i.E (
, )
, $
, and /
Your current Regex is Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor~9999
contains special characters (Regexr explains them better), basically (
and )
denote a capturing group and $
denotes the end of your string. Meaning we'll have to escape them with a \
. That means your Regex (replacesfrom
) is now
@"""Operational Metrics~Copper C1 Cash Costs \(US\$\/lb\) - Lalor~9999"""
Here is a dotnetfiddle showing that it works
Upvotes: 0
Reputation: 76
Regex.Replace works differently than String.Replace. Use
string afterreplace = mainstr.Replace(replacesfrom, replacesto);
Upvotes: 1