我在String.Replace()方法中遇到问题 [英] i have problem in String.Replace() method
本文介绍了我在String.Replace()方法中遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
我在中遇到问题> String.Replace()
方法
a.set(a_Value,comment = a_Comment',report = 0,format ='%s')
如果我使用Replace方法在上面的字符串中替换a,它在String中的每个位置替换a但我只需要替换a而不是a_Value和a_Comment..
Hi
I have problem in String.Replace()
method
"a.set(a_Value, comment= a_Comment', report= 0, format= '%s')"
If I use Replace method in above string to replace "a", it replace "a" every where in String but I need to replace only "a" not "a_Value" and "a_Comment" ..
推荐答案
为什么不直接替换a。用x。或者用什么来替换它?
Why not just replace "a." with "x." or whatever you need to replace it with?
然后替换不适合你 - 使用IndexOf和Substring手动替换数据,或使用Regex进行更复杂的模式匹配和更换。
从你的简短说明中很难说,但如果你想改变:
Then Replace is not for you - either use IndexOf and Substring to replace the data manually, or use a Regex to do a more sophisticated pattern matching and replacement.
From your brief description it is difficult to tell, but if you want to change:
a.set(a_Value, comment= a_Comment', report= 0, format= '%s')
To
To
Replaced.set(a_Value, comment= a_Comment', report= 0, format= '%s')
然后这可能会这样做:
Then this might do it:
Regex reg = new Regex("\\w+(?=\\.set)");
string result = reg.Replace(InputText,"Replaced");
但是很难从单个输入示例中判断出没有输出样本。
But it's difficult to tell from a single example of the input with no output samples.
Hi
Hi
var myString = "a.set a.set(a_Value, comment= a_Comment', report= 0, format= '%s')";
//If you want to replace only 'a.' to something else like 'b.':
var replaced = myString.Replace("a.", "b.");
//If you want to replace all 'a's except 'a_':
var sb = new StringBuilder();
for(var i =0;i<mystring.length;i++)>
{
var c = myString[i];
if (c=='a' && i < myString.Length - 1 && myString[i + 1]!= '_')
{
c = 'b';
}
sb.Append(c);
}
replaced = sb.ToString();
这篇关于我在String.Replace()方法中遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文