我想用c#中的字符串替换字符串中的字符。我尝试过以下几种方法:
在下面的程序中,我希望将字符“:”和第一次出现的“-”之间的字符集替换为其他一些字符。
我可以提取出':‘和'-’第一次出现之间的字符集。
谁能说出如何将它们插入到源字符串中。
string source= "tcm:7-426-8";
string target= "tcm:10-15-2";
int fistunderscore = target.IndexOf("-");
string temp = target.Substring(4, fistunderscore-4);
Response.Write("<BR>"+"temp1:" + temp + "<BR>");示例:
source: "tcm:7-426-8" or "tcm:100-426-8" or "tcm:10-426-8"
Target: "tcm:10-15-2" or "tcm:5-15-2" or "tcm:100-15-2"
output: "tcm:10-426-8" or "tcm:5-426-8" or "tcm:100-426-8"简而言之,我想要替换':‘和’-‘(第一次出现)之间的字符集,并从相同类型的字符串中提取字符。
如何做到这一点可以提供任何帮助。
谢谢。
发布于 2012-04-02 17:20:12
尝试正则表达式解决方案-首先,此方法获取source和target字符串,并在第一个字符串上执行正则表达式替换,目标是'tcm‘之后的第一个数字,该数字必须锚定在字符串的开头。在MatchEvaluator中,它在target字符串上再次执行相同的正则表达式。
static Regex rx = new Regex("(?<=^tcm:)[0-9]+", RegexOptions.Compiled);
public string ReplaceOneWith(string source, string target)
{
return rx.Replace(source, new MatchEvaluator((Match m) =>
{
var targetMatch = rx.Match(target);
if (targetMatch.Success)
return targetMatch.Value;
return m.Value; //don't replace if no match
}));
}注意,如果正则表达式没有在目标字符串上返回匹配项,则不会执行替换。
现在运行这个测试(可能需要将上面的代码复制到测试类中):
[TestMethod]
public void SO9973554()
{
Assert.AreEqual("tcm:10-426-8", ReplaceOneWith("tcm:7-426-8", "tcm:10-15-2"));
Assert.AreEqual("tcm:5-426-8", ReplaceOneWith("tcm:100-426-8", "tcm:5-15-2"));
Assert.AreEqual("tcm:100-426-8", ReplaceOneWith("tcm:10-426-8", "tcm:100-15-2"));
}发布于 2012-04-02 17:16:37
如果您想用target中的内容替换source中的第一个":Number-“,您可以使用以下正则表达式。
var pattern1 = New Regex(":\d{1,3}-{1}");
if(pattern1.IsMatch(source) && pattern1.IsMatch(target))
{
var source = "tcm:7-426-8";
var target = "tcm:10-15-2";
var res = pattern1.Replace(source, pattern1.Match(target).Value);
// "tcm:10-426-8"
}编辑:为了不将字符串替换为空字符串,请在实际替换之前添加一个if子句。
发布于 2012-04-02 17:14:11
我不清楚用于决定使用哪个字符串中的哪个位的逻辑,但仍然应该使用Split(),而不是使用字符串偏移量:(请注意,Remove(0,4)是用来删除tcm:前缀的)
string[] source = "tcm:90-2-10".Remove(0,4).Split('-');
string[] target = "tcm:42-23-17".Remove(0,4).Split('-');现在,您已经在易于访问的数组中获得了来自source和target的数字,因此可以以任何您想要的方式构建新字符串:
string output = string.Format("tcm:{0}-{1}-{2}", source[0], target[1], source[2]);https://stackoverflow.com/questions/9973554
复制相似问题