[英]C# Regex Replacing
So basically, I have a string like this: 所以基本上,我有一个像这样的字符串:
Some Text Here | More Text Here | Even More Text Here
And I want to be able to replace the text between the two bars with New Text
, so it would end up like: 而且我希望能够用
New Text
替换两个小节之间的New Text
,因此最终会像这样:
Some Text Here | New Text | Even More Text Here
I'm assuming the best way is with regexes... so I tried a bunch of things but couldn't get anything to work... Help? 我假设最好的方法是使用正则表达式...所以我尝试了一堆东西,但什么都没用...帮助吗?
For a simple case like this, the best apprach is a simple string split: 对于这样的简单情况,最好的方法是简单的字符串拆分:
string input = "foo|bar|baz";
string[] things = input.Split('|');
things[1] = "roflcopter";
string output = string.Join("|", things); // output contains "foo|roflcopter|baz";
This relies on a few things: 这取决于几件事:
To correct the second, do something like: 要纠正第二个问题,请执行以下操作:
for (int i = 0; i < things.Length; ++i)
things[i] = things[i].Trim();
To remove whitespace from the beginning and end of each element. 从每个元素的开头和结尾删除空格。
The general rule with regexes is that they should usually be your last resort; 正则表达式的一般规则是,它们通常应该是您的最后选择。 not your first.
不是你的第一个。 :)
:)
If you want to use regex...try this: 如果要使用正则表达式...请尝试以下操作:
String testString = "Some Text Here | More Text Here | Even More Text Here";
Console.WriteLine(Regex.Replace(testString,
@"(.*)\|([^|]+)\|(.*)",
"$1| New Text |$3",
RegexOptions.IgnoreCase));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.