删除特定字符串我想如果存在正则表达式,如果存在
所以
ABCD => ABCD
ABCD-L => ABCD
此刻我正在使用类似的线从我的字符串的末尾删除-L
低于在我的正则表达式中使用if/else
类型的排列,但是,我有一种感觉,它应该比这更容易。
var match = Regex.Match("...", @"(?(\S+-L$)\S+(?=-L)|\S+)");
删除特定字符串我想如果存在正则表达式,如果存在
所以
ABCD => ABCD
ABCD-L => ABCD
此刻我正在使用类似的线从我的字符串的末尾删除-L
低于在我的正则表达式中使用if/else
类型的排列,但是,我有一种感觉,它应该比这更容易。
var match = Regex.Match("...", @"(?(\S+-L$)\S+(?=-L)|\S+)");
如何只是在做:
Regex rgx = new Regex("-L$");
string result = rgx.Replace("ABCD-L", "");
所以基本上:如果字符串以-L
结束时,替换为空字符串的一部分。
如果您不仅希望在字符串末尾调用替换,还要在字末尾调用替换,您还可以添加一个额外开关来检测字符边界(\b
)以及字符串末尾:
Regex rgx = new Regex("-L(\b|$)");
string result = rgx.Replace("ABCD-L ABCD ABCD-L", "");
请注意,检测字边界可能有点模糊。请参阅here以获取C#中被认为是单词字符的字符列表。
使用Regex.Replace
功能,
Regex.Replace(string, @"(\S+?)-L(?=\s|$)", "$1")
说明:
( group and capture to \1:
\S+? non-whitespace (all but \n, \r, \t, \f,
and " ") (1 or more times)
) end of \1
-L '-L'
(?= look ahead to see if there is:
\s whitespace (\n, \r, \t, \f, and " ")
| OR
$ before an optional \n, and the end of
the string
) end of look-ahead
您还可以使用与string.replace()方法查找字符串中的特定字符串,在这种情况下用另一个字符串替换为空字符串。
http://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx
您当然可以使用正则表达式这一点,但为什么用普通的字符串函数时更清晰?
比较:
text = text.EndsWith("-L")
? text.Substring(0, text.Length - "-L".Length)
: text;
这样:
text = Regex.Replace(text, @"(\S+?)-L(?=\s|$)", "$1");
或者更好的是,像这样定义一个扩展方法:
public static string RemoveIfEndsWith(this string text, string suffix)
{
return text.EndsWith(suffix)
? text.Substring(0, text.Length - suffix.Length)
: text;
}
然后你的代码可以是这样的:
text = text.RemoveIfEndsWith("-L");
当然,你总是可以使用Regex定义扩展方法。至少你的调用代码看起来更清晰,并且更具可读性和可维护性。
您的比较错误。你应该将你的解决方案与新的Regex(“ - L $”)进行比较。替换(text,“”);' – 2014-11-06 02:27:21
@RobbyCornelissen - 这段代码肯定比我用过的正则表达式更好,但它仍然不太明显到它做什么。 – Enigmativity 2014-11-06 03:57:17
和'string.Replace和string.Contains'方法不适合你..? [String.Replace(string,string)](http://msdn.microsoft.com/en-us/library/fk49wtc1(v = vs.110)。aspx) – MethodMan 2014-11-06 02:02:52
这是相当大的正则表达式的一部分,如果我想把它分解成一个C#代码,它将转化为相当数量的行。就这样。 – Mehrad 2014-11-06 02:05:29
再次为什么使用正则表达式,如果你不明白它..使用string.Replace它更容易理解和并入string.Contains方法 – MethodMan 2014-11-06 02:06:20