gpt4 book ai didi

c# - 正则表达式包含 [ :alnum:] POSIX character class did not match string with C#, 但在线工具评估正常

转载 作者:行者123 更新时间:2023-11-30 22:52:44 24 4
gpt4 key购买 nike

我有一个正则表达式

(?'Conpany'Company) - (?'Model'Model) - (?'Version'V(?'Major'\d+).(?'Minor'\d+).(?'Bugfix'\d+).(?'Build'\d+)(?'PreRelease'-[[:alnum:]]*)?(?'Meta'\+[[:alnum:]]*)?) - (?'CompileDate'(?'Year'\d{4})(?'Month'\d{2})(?'Day'\d{2}))

应该匹配 SCPI 字符串

Company - Model - V1.0.0.1718-RC1 - 20190821

如果我使用在线工具尝试正则表达式,一切正常并且字符串与正则表达式匹配。

现在我正在尝试将正则表达式与 C# 一起使用来评估命令答案,但结果始终为 false

    var regex = @"(?'Conpany'Company) - (?'Model'Model) - (?'Version'V(?'Major'\d+).(?'Minor'\d+).(?'Bugfix'\d+).(?'Build'\d+)(?'PreRelease'-[[:alnum:]]*)?(?'Meta'\+[[:alnum:]]*)?)" - (?'CompileDate'(?'Year'\d{4})(?'Month'\d{2})(?'Day'\d{2}))";

//
responce = await rs232Device.SendCommand(query, DefaultTimeout);

var match = Regex.Match(responce.Message, regex, RegexOptions.IgnoreCase);
//
Assert.That(match.Success, Is.True);

我发现编译日期 - (?'CompileDate'(?'Year'\d{4})(?'Month'\d{2})(?'Day'\d{2 })) 从正则表达式来看一切都很好。

但我不知道为什么它不能在 C# 中使用完整的正则表达式,而 https://regex101.com/可以匹配字符串。

最佳答案

.NET 正则表达式引擎不支持 POSIX 字符类。你在这里有 [[:alnum:]] ,将其替换为 \w (任何 word char ),或 [\p{L}\p{ N}](任何字母或数字)或 [^\W\p{Pc}](除连接标点符号如 _ 之外的任何单词字符)将让它起作用。

查看其他 POSIX 字符类示例映射(它们可能无法完全相同但至少相似):

POSIX        .NET             Description[:alpha:]   \p{L}           Any letters (\p{L} matches only those from the BMP plane)[:alnum:]   [\p{L}\p{N}]    Any letters or digits[:digit:]   \p{N} or \d     Any digits (there is also a [:d:] POSIX variation)[:space:]   \s or \p{Z}     Any whitespace[:blank:]   [\p{Zs}\t]      Any horizontal whitespace

Besides, some extend them to

POSIX        .NET             Description[:ascii:]   [\x00-\x7E]     ASCII character set[:xdigit:]  [0-9a-fA-F]     Chars that are used to define hex values

Besides, you must escape literal dots in the pattern.

Also, always use the Web regex tester that is compatible with the regex engine you plan to use with your pattern.

(?'Conpany'Company) - (?'Model'Model) - (?'Version'V(?'Major'\d+)\.(?'Minor'\d+)\.(?'Bugfix'\d+)\.(?'Build'\d+)(?'PreRelease'-\w*)?(?'Meta'\+\w*)?) - (?'CompileDate'(?'Year'\d{4})(?'Month'\d{2})(?'Day'\d{2}))

参见 regex demo

enter image description here

关于c# - 正则表达式包含 [ :alnum:] POSIX character class did not match string with C#, 但在线工具评估正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57822008/

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