c# - 正则表达式匹配一个或两个数字

标签 c# regex

如果这样

(°[0-5])

匹配°4

还有这个

((°[0-5][0-9]))

匹配°44

为什么会这样

((°[0-5])|(°[0-5][0-9]))

匹配 °4 但不匹配 °44?

最佳答案

因为当您在正则表达式中使用逻辑或时,正则表达式引擎会在找到与正则表达式第一部分(此处为 °[0-5])的匹配项时返回第一个匹配项,在这种情况下,因为°[0-5]°44 中匹配 °4 它返回 °4 并且不会继续匹配另一种情况(此处 °[0-5][0-9]):

((°[0-5])|(°[0-5][0-9]))

A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy. To match a literal '|', use \|, or enclose it inside a character class, as in [|].

关于c# - 正则表达式匹配一个或两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31548679/

相关文章:

c# - 从 .NET C# 运行 Gulp 任务?

c# - 具有多个变量的 using 语句

Javascript 正则表达式反向引用未填充所有捕获组

python - 正则表达式 GUI?

c# - 提取键值对

远程计算机中的 C# 任务计划程序

c# - 简单的普通 Windows 应用程序——我应该从 WPF 还是 WinForms 开始?

c# - 获取 C# WinForms App 的应用程序图标

c# - 如何避免特定字符串模式被 Regex.replace () 替换

java - 正则表达式 - 从 Java 中的字符串中提取信息