Reputation: 157
As the title, I'm supposed to get some sub-strings from a string which looks like this: "-23/45 + 14/9". What I need to get from that string is the four numbers and the operator in the middle. What has confused me is that how to use only one regular expression pattern to do this. Below is the requirement:
Write a regular expression patt that can be used to extract (numerator,denominator,operator,numerator,denominator) from a string containing a fraction, an arithmetic operator, and a fraction. You may assume there is a space before and after the arithmetic operator and no spaces surrounding the / character in a fraction. And all fractions will have a numerator and denominator. Example:
>>> s = "-23/45 + 14/9"
>>> re.findall(patt,s)
[( "-23","45","+","14","49")]
>>> s = "-23/45 * 14/9"
>>> re.findall(patt,s)
[( "-23","45","*","14","49")]
In general, your code should handle any of the operators +, -, * and /. Note: the operator module for the two argument function equivalents of the arithmetic (and other) operators
My problem here is that how to use only one regular expression to do this. I have thought about getting the sub strings contain numbers and stop at any character which is not a number, but this will miss the operator in the middle. Another idea is to include all the operators( + - * /) and stop at white space, but this will make first and last two numbers become together. Can anybody give me a direction how to solve this problem with only one regular expression pattern? Thanks a lot!
Upvotes: 1
Views: 690
Reputation: 10360
Try this regex:
(-?\d+)\s*\/\s*(\d+) *([+*\/-])\s*(-?\d+)\s*\/(\d+)
You can extract the required information from Group 1 to Group 5
Explanation:
(-?\d+)
- matches an optional -
followed by 1+ occurrences of a digit and capture it in Group 1\s*\/\s*
- matches 0+ occurrences of a whitespace followed by a /
followed by 0+ occurrences of a whitespace(\d+)
- matches 1+ occurrences of a digit and capture it in Group 2*
- matches 0+ occurrences of a space([+*\/-])
- matches one of the operators in +
,-
,/
,*
and captures it in Group 3\s*
- matches 0+ occurrences of a whitespace(-?\d+)
- matches an optional -
followed by 1+ occurrences of a digit and capture it in Group 4\s*\/
- matches 0+ occurrences of a whitespace followed by /
(\d+)
- matches 1+ occurrences of a digit and capture it in Group 5Upvotes: 1