4

我是 Perl 和正则表达式世界的新手,我正在尝试编写一个匹配 0.0 到 4.0 之间的 GPA 的正则表达式。所有匹配值只能是由句点(1.23.40.2等)分隔的 2 位数字。

^[0]|[0-3]\.(\d?\d?)|[4].[0]$

这是我所拥有的,但它不正确,因为它匹配“1.22”、“4a0”、“14.0”和“2.”。如果有人有任何建议,他们将不胜感激。

4

3 回答 3

4

这里的几个答案似乎不必要地复杂。相反,这个简单的正则表达式应该这样做:[0-3]\.\d|4\.0,假设单位数形式(例如'1')不是有效输入。(我们不使用我所在的 GPA,所以我不知道这是否是一个安全的假设。)

前后都有锚,正如我在这里看到的其他人使用的那样:

^([0-3]\.\d|4\.0)$

或者,如果您不需要捕获组:

^(?:[0-3]\.\d|4\.0)$

完整解释:正则表达式匹配0、1、2 或 3,后跟句点和任何单个数字,或文字字符串 4.0

于 2013-04-28T22:11:36.213 回答
0

Try this:

(?<!\d)([0-3](\.\d?)|4(\.0)?)(?!\d)

It uses (?<! ) and (?! ) which is called negative look behind and negative look ahead. This makes sure that \d is not present before or after the regex. It is not matched in the regex, just checking it is not after it. Also, with this regex, you are not limited to values being separated by lines.

(Modified according to caimarvo suggestion)

于 2013-04-26T03:05:16.420 回答
0
^[0-3]{1}(\.\d{1}?)(?!\d)|(?<!.)4\.0?(?!.)$

这行得通,同样的想法会前后观察额外的字符。

于 2013-04-28T21:06:51.510 回答