【问题标题】:How to match a string, ignoring ending newline?如何匹配字符串,忽略结束换行符?
【发布时间】:2010-11-23 02:45:46
【问题描述】:

我希望能够将整个字符串(因此单词边界)与模式“ABC”匹配(“ABC”只是为了方便起见,我不想检查固定字符串是否相等),所以换行对我来说很重要。但是,将单个“\n”放在字符串末尾时似乎会被忽略。我的模式有问题吗?

Regex r = new Regex(@"^ABC$");
string[] strings =
{
    "ABC",//True
    "ABC\n",//True: But, I want it to say false.
    "ABC\n\n",//False
    "\nABC",//False
    "ABC\r",//False
    "ABC\r\n",//False
    "ABC\n\r"//False
};
foreach(string s in strings)
{
    Console.WriteLine(r.IsMatch(s));
}

【问题讨论】:

    标签: c# .net regex


    【解决方案1】:

    试试这个(未测试):

    Regex r = new Regex(@"\AABC\z");
    

    \A = 字符串开头的锚点
    \z = 字符串结尾的锚点
    ^ = 行首的锚点
    $ = 行尾的锚点

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-18
    • 2017-12-10
    • 2011-09-28
    • 2019-05-13
    • 1970-01-01
    • 2013-11-19
    • 2017-12-30
    相关资源
    最近更新 更多