(\d)(?: /|/ | / )(\d)
should do it (and only return incorrectly entered fractions). Notice the use of no-capture groups.
Edit: updated with comments below.
Question
I am trying to make a regex that will find certain cases of incorrectly entered fractions, and return the numerator and denominator as groups.
These cases involve a space between the slash and a number: such as either 1 /2
or 1/ 2
.
I use a logical-or operator in the regex, since I'd rather not have 2 separate patterns to check for:
r'(\d) /(\d)|(\d)/ (\d)'
(I'm not using \d+
since I'm more interested in the numbers directly bordering the division sign, though \d+
would work as well).
The problem is, when it matches one of the cases, say the second (1/ 2
), looking at all the groups gives (None, None, '1', '2')
, but I would like to have a regex that only returns 2 groups--in both cases, I would like the groups to be ('1', '2'). Is this possible?
Edit:
I would also like it to return groups ('1', '2') for the case 1 / 2
, but to not capture anything for well-formed fractions like 1/2
.
Solution
(\d)(?: /|/ | / )(\d)
should do it (and only return incorrectly entered fractions). Notice the use of no-capture groups.
Edit: updated with comments below.
OTHER TIPS
What about just using (\d)\s*/\s*(\d)
?
That way you will always have only two groups:
>>> import re
>>> regex = r'(\d)\s*/\s*(\d)'
>>> re.findall(regex, '1/2')
[('1', '2')]
>>> re.findall(regex, '1 /2')
[('1', '2')]
>>> re.findall(regex, '1/ 2')
[('1', '2')]
>>> re.findall(regex, '1 / 2')
[('1', '2')]
>>>