Andrew Serra
Andrew Serra

Reputation: 163

Trouble locating regex mistake

import re

reg = r'^[(][+-]?([0]|([1-9][0-9]*)\.?\d+?),\s[+-]?([0]|([1-9][0-9]*)\.?\d+?)[)]$'
for _ in range(int(input())):
    coord = input()
    if re.search(reg, coord):
        if 0 <= float(re.search(reg, coord).group(1)) <= 90 and 0 <= float(re.search(reg, coord).group(3)) <= 180:
            print('Valid')
        else: print('Invalid')
    else: print('Invalid')

Here is my code for a regular expression that finds coordinates. I had trouble finding the mistake in the regular expression. The test cases that do not work are (-6, -165) and (-6, -172) What is the problem that prevents the code to enter the first if statement?

Upvotes: 1

Views: 32

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

The main issue is that \d+? matches 1 or more digits, as few as possible, while you assumed it matches 0 or more digits.

To make .xxx part optional, use an optional non-capturing group (?:\.\d+)?:

^\([+-]?((?:0|[1-9][0-9]*)(?:\.\d+)?),\s[+-]?((?:0|[1-9][0-9]*)(?:\.\d+)?)\)$

See the regex demo

The part that matches a number, (?:0|[1-9][0-9]*)(?:\.\d+)?, now matches:

  • (?:0|[1-9][0-9]*) - a non-capturing group matching either of the 2 alternatives:
    • 0 - a zero
    • | - or
    • [1-9][0-9]* - a digit from 1 to 9 and then any 0+ digits
  • (?:\.\d+)? - an optional non-capturing group matching 1 or 0 occurrences of:
    • \. - a dot
    • \d+ - 1 or more digits.

Upvotes: 1

Related Questions