如果这样
(°[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/