Regex for GPA in Perl

I'm new to Perl and the Regexes world, and I'm trying to write a regex that matches the GPA between 0.0 and 4.0. All matching values ​​can be only two digits separated by a period ( 1.2 , 3.4 , 0.2 , etc.).

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

This is what I have, but it is incorrect, because it corresponds to "1.22", "4a0", "14.0" and "2.". If anyone has any suggestions, they would be greatly appreciated.

+4
source share
3 answers

A few answers here seem overly complex. Instead, this simple regular expression should do this: [0-3]\.\d|4\.0 , assuming that the one-bit form (for example, "1") is invalid. (We do not use the GPA from where I come from, so I don’t know if this is a safe guess.)

With anchors in front and behind, as I see others here use:

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

Or if you do not need a capture group:

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

Full explanation: the regular expression matches either 0, 1, 2, or 3, followed by a period and any single digit or literal string 4.0.

+4
source

Try the following:

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

It uses (?<! ) And (?! ) , Which is called negative appearance and negative look. This ensures that \d absent before or after the regular expression. It does not match in a regular expression, just checking that it is not after it. Also, with this regex you are not limited to values ​​shared by strings.

(Modified according to caimarvo proposal)

0
source
 ^[0-3]{1}(\.\d{1}?)(?!\d)|(?<!.)4\.0?(?!.)$ 

It works, the same idea looks ahead and lags behind additional characters.

0
source

All Articles