【问题标题】:Find exact characters in string using regex使用正则表达式查找字符串中的确切字符
【发布时间】:2015-04-16 20:15:19
【问题描述】:

我有如下字符串

M10 end 
start M11
M1
M1 start
M n1
end M1

我想要实现的是使用正则表达式获得只有“M1”的结果。

这是我当前的代码

Regex r = new Regex("^M1$|M1$");

输出如下所示,其中缺少字符串“M1 start”

M1
end M1

【问题讨论】:

  • 您是否也希望它与start M1 end 匹配?

标签: c# regex


【解决方案1】:
Regex r = new Regex("^.*\\bM1\\b.*$");

这应该为你做。参见演示。这里\b 是单词边界,它只匹配M1 而不是M10

\b 在单词边界处断言位置 (^\w|\w$|\W\w|\w\W)

https://regex101.com/r/sJ9gM7/113

【讨论】:

    【解决方案2】:

    好吧,如果你不想过度使用Regex,你可以使用

    target="M1";
    if( underTest.IndexOf(target) == 0 && underTest.Lenght == target.Lenght)
    {
     ....
    }
    

    使用StringReader 分割每一行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多