给出以下字符串:
string s = "I need drop the 1 from the end of AAAAAAAA1 and BBBBBBBB1"
如何从任何以1结尾的8个字符串中修剪“1”?我到目前为止找到了一个可以找到这些字符串的Regex模式,我猜我可以使用TrimEnd删除“1”,但我该如何修改字符串呢?
Regex regex = new Regex("\\w{8}1");
foreach (Match match in regex.Matches(s))
{
MessageBox.Show(match.Value.TrimEnd('1'));
}
我正在寻找的结果是“我需要从AAAAAAAA和BBBBBBBB结束时放弃1”
答案 0 :(得分:4)
Regex.Replace
是工作的工具:
var regex = new Regex("\\b(\\w{8})1\\b");
regex.replace(s, "$1");
我稍微修改了正则表达式,以便与您尝试更紧密地做的事情的描述相匹配。
答案 1 :(得分:0)
这是一种非正则表达式方法:
s = string.Join(" ", s.Split().Select(w => w.Length == 9 && w.EndsWith("1") ? w.Substring(0, 8) : w));
答案 2 :(得分:0)
在VB中使用LINQ:
Dim l = 8
Dim s = "I need drop the 1 from the end of AAAAAAAA1 and BBBBBBBB1"
Dim d = s.Split(" ").Aggregate(Function(p1, p2) p1 & " " & If(p2.Length = l + 1 And p2.EndsWith("1"), p2.Substring(0, p2.Length - 1), p2))
答案 3 :(得分:-1)
试试这个:
s = s.Replace(match.Value, match.Value.TrimEnd('1'));
s字符串将具有您想要的值。