【问题标题】:How to trim characters from certain patterned words in string?如何从字符串中的某些模式单词中修剪字符?
【发布时间】:2013-01-31 16:15:21
【问题描述】:

给定以下字符串:

string s = "I need drop the 1 from the end of AAAAAAAA1 and BBBBBBBB1"

如何从任何以 1 结尾的 8 个字符的字符串中去除“1”?我到目前为止找到了一个可以找到这些字符串的工作正则表达式模式,我猜我可以使用 TrimEnd 删除“1”,但是我该如何修改字符串本身呢?

Regex regex = new Regex("\\w{8}1");

foreach (Match match in regex.Matches(s))
{
    MessageBox.Show(match.Value.TrimEnd('1'));
}

我正在寻找的结果是“我需要从 AAAAAAAAA 和 BBBBBBBB 末尾删除 1”

【问题讨论】:

  • 这八个字符需要相同吗?
  • 如果你有正则表达式来查找需要删除的字符,那么使用Regex.Replace:msdn.microsoft.com/en-us/library/…
  • 如果是任何 8 个字符的字符串,为什么你需要正则表达式,除非你的意思是子字符串?
  • 这 8 个字符不必相同。它们是数据库中的表名,因此实际上看起来像“TBLACUST1”或“TBLBPROD1”

标签: c# regex


【解决方案1】:

Regex.Replace 是工作的工具:

var regex = new Regex("\\b(\\w{8})1\\b");
regex.replace(s, "$1");

我稍微修改了正则表达式,以更贴近您想要做的事情的描述。

【讨论】:

  • “$1”是我不知道该怎么做的部分。谢谢!!这非常有效。
  • 我建议改为new Regex(@"\b(\w{8})1\b") - 我发现没有双反斜杠会更容易阅读。
【解决方案2】:

这里是非正则表达式方法:

s = string.Join(" ", s.Split().Select(w => w.Length == 9 && w.EndsWith("1") ? w.Substring(0, 8) : w));

【讨论】:

    【解决方案3】:

    在带有 LINQ 的 VB 中:

    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))
    

    【讨论】:

    • 没关系。我是来查看这个问题的VB开发人员,可能还有其他人和我一样。我在帖子开头指出了语言。
    【解决方案4】:

    试试这个:

    s = s.Replace(match.Value, match.Value.TrimEnd('1'));
    

    并且 s 字符串将具有您想要的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多