gpt4 book ai didi

c# - 正则表达式选项 "Multiline"

转载 作者:太空狗 更新时间:2023-10-29 23:37:00 26 4
gpt4 key购买 nike

我有一个正则表达式来匹配带逗号的日期格式。

yyyy/mm/dd or yyyy/mm

例如:

2016/09/02,2016/08,2016/09/30

我的代码:

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

我使用选项多行。如果字符串数据有“\n”。任何字符都将匹配此正则表达式。

例如:

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

I find option definition in MSDN .它说:

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.

我不明白为什么会出现这个问题。任何人都可以解释它吗?谢谢。

最佳答案

您的正则表达式可以匹配您在字符串末尾添加换行符后得到的空行。 "test\n" 包含两行,第二行匹配。

以自由间距模式查看您的正则表达式模式:

^                 # 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

如果你不希望它匹配空行,将最后的)*替换为)+

另一种方法是使用更展开的模式,例如

^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]))?)*$

参见 regex demo .在代码内部,建议使用 block 并动态构建模式:

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

如您所见,第一个 block (在 ^ anchor 行开始之后)在这里是必须的,因此永远不会匹配空行。

关于c# - 正则表达式选项 "Multiline",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39286641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com