简体   繁体   English

正则表达式选项“Multiline”

[英]Regex option “Multiline”

I have a regex to match date format with comma. 我有一个正则表达式匹配日期格式与逗号。

yyyy/mm/dd or yyyy/mm yyyy / mm / dd或yyyy / mm

For example: 例如:

2016/09/02,2016/08,2016/09/30 2016/09 / 02,2016 / 08,2016 / 9月30日

My code: 我的代码:

string data="21535300/11/11\n";
Regex reg = new Regex(@"^(20\d{2}/(0[1-9]|1[012])(/(0[1-9]|[12]\d|30|31))?,?)*$", 
                      RegexOptions.Multiline);

if (!reg.IsMatch(data))
    "Error".Dump();
else
    "True".Dump();

I use option multiline. 我使用选项多线。 If string data have "\\n". 如果字符串数据有“\\ n”。 Any character will match this regex. 任何角色都会匹配此正则表达式。

For example: 例如:

string data="test\n"
string data="2100/1/1"

I find option definition in MSDN . 我在MSDN中找到了选项定义 It says: 它说:

It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string. 它改变了^和$语言元素的解释,使它们匹配行的开头和结尾,而不是输入字符串的开头和结尾。

I didn't understand why this problem has happened. 我不明白为什么会出现这个问题。 Anyone can explan it? 有人可以解释一下吗? Thanks. 谢谢。

Your regex can match an empty line that you get once you add a newline at the end of the string. 您的正则表达式可以匹配在字符串末尾添加换行符后得到的空行。 "test\\n" contains 2 lines, and the second one gets matched. "test\\n"包含2行,第二行匹配。

See your regex pattern in a free-spacing mode: 以自由间距模式查看正则表达式模式:

^                 # Matches the start of a line
 (                # Start of Group 1
   20\d{2}/
   (0[1-9]|1[012])
   (/
     (0[1-9]|[12]\d|30|31)
   )?,?
 )*                # End of group 1 - * quantifier makes it match 0+ times
$                  # End of line

If you do not want it to match an empty line, replace the last )* with )+ . 如果您不希望它与空行匹配,请将最后一个)*替换为)+

An alternative is to use a more unrolled pattern like 另一种方法是使用更多展开的模式

^20\d{2}/(0[1-9]|1[012])(/(0[1-9]|[12]\d|3[01]))?(,20\d{2}/(0[1-9]|1[012])(/(0[1-9]|[12]\d|3[01]))?)*$

See the regex demo . 请参阅正则表达式演示 Inside the code, it is advisable to use a block and build the pattern dynamically: 在代码内部,建议使用块并动态构建模式:

string date = @"20\d{2}/(0[1-9]|1[012])(/(0[1-9]|[12]\d|3[01]))?";
Regex reg = new Regex(string.Format("^{0}(,{0})*$", date), RegexOptions.Multiline);

As you can see, the first block (after the start of the line ^ anchor) is obligatory here, and thus an empty line will never get matched. 正如您所看到的,第一个块(在行^锚点之后)是强制性的 ,因此空行永远不会匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM