.NET的Regex类和新行 [英] .NET's Regex class and newline

查看:101
本文介绍了.NET的Regex类和新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不.NET的正则表达式对待\\\
作为行结束字符

Why doesn't .NET regex treat \n as end of line character?

示例代码:

string[] words = new string[] { "ab1", "ab2\n", "ab3\n\n", "ab4\r", "ab5\r\n", "ab6\n\r" };
Regex regex = new Regex("^[a-z0-9]+$");
foreach (var word in words)
{
    Console.WriteLine("{0} - {1}", word, regex.IsMatch(word));
}



这是我得到的回应:

And this is the response I get:

ab1 - True
ab2
 - True
ab3

 - False
 - False
ab5
 - False
ab6
 - False

为什么正则表达式匹配 ab2\\\

Why does the regex match ab2\n?

更新:
口不认为多行是一个很好的解决方案,那就是,我想验证的登录只匹配指定的字符,并且它必须是单行。如果我改变了多行选项AB1,AB2,AB3和AB6匹配构造函数的表达式,AB4和AB5不匹配。

Update: I don't think Multiline is a good solution, that is, I want to validate login to match only specified characters, and it must be single line. If I change the constructor for MultiLine option ab1, ab2, ab3 and ab6 match the expression, ab4 and ab5 don't match it.

推荐答案

如果字符串以行结束打破了 RegexOptions.Multiline 将不起作用。在 $ 会忽略最后换行符,因为有后罢了。

If the string ends with a line break the RegexOptions.Multiline will not work. The $ will just ignore the last line break since there is nothing after that.

如果要匹配,直到字符串的结尾,而忽略休息使用的任何行 \z

If you want to match till the very end of the string and ignore any line breaks use \z

Regex regex = new Regex(@"^[a-z0-9]+\z", RegexOptions.Multiline);

这是为MutliLine和单线,这并不重要。

This is for both MutliLine and SingleLine, that doesn't matter.

这篇关于.NET的Regex类和新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆