C# 正则表达式清理字符串
我有以下字符串:C# 正则表达式清理字符串,c#,regex,string,C#,Regex,String,我有以下字符串: Fox跳过绳子(1):AB 123 我正试图用C#中的正则表达式来清理这个问题。我需要它,就像: 狐狸跳过绳子 我无法使用正则表达式匹配此字符串 string badstring = "Fox jumps over the rope (1):AB 123"; string goodstring = Regex.Replace(strIn, @"[^\w\.@-]", "", RegexOptions.None,
Fox跳过绳子(1):AB 123
我正试图用C#中的正则表达式来清理这个问题。我需要它,就像:
狐狸跳过绳子
我无法使用正则表达式匹配此字符串
string badstring = "Fox jumps over the rope (1):AB 123";
string goodstring = Regex.Replace(strIn, @"[^\w\.@-]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
要删除的字符串应与括号内的数字及其后面的所有文本匹配
String Pattern = "[^a-zA-Z\\s]+[a-zA-Z]*";
String StringToClean = "Fox jumps over (1):AB 123 the rope (1):AB 123";
String StringCleaned = Regex.Replace(StringToClean, @Pattern, "");
String Cleaned = Regex.Replace(StringCleaned, @"[\s]+", " ");
Console.WriteLine(Cleaned);
结果=狐狸跳过绳子
测试
在C#中测试:如果您想删除后缀(“(1):AB 123”
,您可以尝试使用Linq而不是正则表达式:在TakeWhile
的帮助下,我们将获得所有必需的字符,直到后缀出现
using System.Linq;
...
string raw = "Fox jumps over the rope (1):AB 123";
// "Fox jumps over the rope "
string cleared = string.Concat(raw
.TakeWhile(c => char.IsLetter(c) || char.IsWhiteSpace(c)));
你可以用
Regex.Replace(badstring, @"\s*\(\d+\).*", "")
\s*\(\d+\).
regex匹配
-0+空格字符\s*
-a\(\d+\)
,然后是1+位,(
)
-行的其余部分*
Regex.Replace
用空字符串替换所有不重叠的匹配项。您试图删除的模式是什么?请尝试Regex.Replace(badstring,@“\s*\(\d+\).*”,“”)
@Wiktor,这非常有效。请你把这个作为一个答案,并向我解释更多关于你是如何把正则表达式组合在一起的。我在正则表达式方面有点弱,正在努力学习。谢谢。已发布。这对C#不起作用。AB仍然存在。输出为:Fox跳过绳子AB
var s = "Fox jumps over the rope (1):AB 123";
var x = s.Substring(0, s.IndexOf("(") - 1);
// or: var x = s.Split(" (")[0];