-1

So I made a regex to test valid GPAs such as 0.00 through 5.00 including things like 0, 4, 3.55, etc. Things that aren't valid include 6.0, 3.555, 0.000, 11.11, etc. On multiple websites I have verified that this Regex works for those cases.

(([0-5]\s)|([0-4]\.\d{0,2}\s))|[5]\.[0]{0,2}\s

However then I try and use this in Kotlin using the Java Regex class I'm not getting the expected results, always false for my test cases.

Code with "2.0" test string:

Regex("(([0-5]\\s)|([0-4]\\.\\d{0,2}\\s))|[5]\\.[0]{0,2}\\s").matches("2.0")

I'm curious what I'm missing that is causing this to fail. I've escaped / characters and tried variations using string literals with no escaping, and also using Pattern/Matcher directly to no avail.

Devun
  • 1
  • 2
  • 1
    Note that `\s` matches a whitespace char, and `2.0` string has no whitespace after `0`. You may use `"""[0-4](?:\.\d{0,2})?|5(?:\.0{0,2})?"""` to match your string. See https://rextester.com/VJX10843 – Wiktor Stribiżew Dec 18 '18 at 18:16
  • Your original regex isn't correct as it matches `4.` or `3.` and you really don't need to have two alternations just for handling `5` GPA and the way you are doing isn't fully correct. You can use this regex `^(?:5(?:\.0{1,2})?|[0-4](?:\.\d{1,2})?)$` [Demo here](https://regex101.com/r/S1E767/1) – Pushpesh Kumar Rajwanshi Dec 18 '18 at 18:21

1 Answers1

0

^(?:5(?:\.0{1,2})?|[0-4](?:\.\d{1,2})?)$ from @Pushpesh Kumar Rajwanshi's comment fixed my issue. Thanks for the prompt response and catching the missing 4. case.

Devun
  • 1
  • 2