去除串想,如果我可以写正则表达式来做到以下,目前使用String.Remove(17,7)正则表达式从字符串
string txt = "werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222";
我想从上面的字符串
去除串想,如果我可以写正则表达式来做到以下,目前使用String.Remove(17,7)正则表达式从字符串
string txt = "werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222";
我想从上面的字符串
txt = txt.Replace(".zip.ytu", "");
你为什么不简单地在上面做?
使用与string.replace:
txt = txt.Replace(".zip.ytu", "");
下面是使用正则表达式的任择议定书要求的答案。 ;-)
要使用正则表达式,把replacment文本匹配(),然后替换匹配任何内容(的String.Empty):
string text = @"werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222";
string pattern = @"(\.zip\.ytu)";
Console.WriteLine(Regex.Replace(text, pattern, string.Empty));
// Outputs
// werfds_tyer.abc_20111223170226_20111222.20111222
HTH
真的不知道什么是“.zip.ytu”,但如果你并不需要精确匹配,你可能会使用类似的东西:
string txt = "werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222";
Regex mRegex = new Regex(@"^([^.]*\.[^.]*)\.[^.]*\.[^_]*(_.*)$");
Match mMatch = mRegex.Match(txt);
string new_txt = mRegex.Replace(txt, mMatch.Groups[1].ToString() + mMatch.Groups[2].ToString());
[^。] *(零到无限)不是一段时间。为什么用'*'杀死正则表达式解析器,特别是零条件有效?相反,对许多人使用“+”表示-1-会提供更好的提示,而不会导致回溯。你真的相信随着时间的推移,什么也没有;或者你认为至少有一个角色会存在?如果你相信1个字符将存在,那么使用它而不是*。 HTH – OmegaMan 2011-12-28 01:44:39
我写道,我不知道什么是“.zip.ytu”,而且,我不知道整个字符串是什么。所以,我可以承认这个字符串可能类似“..test1.test2_123123.123123”,因为为什么不呢?如果我真的知道这些点之间总会有东西,那么当然,我会用“+”而不是“*”。怎么了? – 2011-12-28 04:34:54
这里是我使用更复杂的repaces的方法。查看链接:http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(v=vs.110).aspx正则表达式替换。我还添加了下面的代码。
string input = "This is text with far too much " +
"whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
LOL ...简单的岩石:) – user570715 2011-12-27 19:17:17