2015-11-13 49 views
0

我需要一个正则表达式来解析包含分数和操作的字符串[+, -, *, or /]并返回包含分子,分母和使用findall函数中的re的5元素元组模块。正则表达式使用python re模块的分数数学表达式

实施例:str = "15/9 + -9/5"

输出应形式[("15","9","+","-9","5")]

我能够想出这个的:

pattern = r'-?\d+|\s+\W\s+' 

print(re.findall(pattarn,str)) 

其产生["15","9"," + ","-9","5"]的输出。但是经过这么长时间的摆弄之后,我无法把它变成一个5元组元组,而且如果没有匹配周围的空白区域,我也无法匹配这个操作。

+0

“[tuple([”15“,”9“,”+“,”-9“,”5“])]产生了[(”15“,”9“,” +“,”-9“,”5“)]'?你是否也需要摆脱空白?如果是这样,[[15],[9],[+],“-9”,“5”]]]]中的[[tuple([x.replace('','')] [(“15”,“9”,“+”,“-9”,“5”)]。 – dorverbin

回答

0

这种模式将工作:

(-?\d+)\/(\d+)\s+([+\-*/])\s+(-?\d+)\/(\d+) 
#lets walk through it 
(-?\d+) #matches any group of digits that may or may not have a `-` sign to group 1 
     \/ #escape character to match `/` 
     (\d+) #matches any group of digits to group 2 
       \s+([+\-*/])\s+ #matches any '+,-,*,/' character and puts only that into group 3 (whitespace is not captured in group) 
           (-?\d+)\/(\d+) #exactly the same as group 1/2 for groups 4/5 

演示了这一点:

>>> s = "15/9 + -9/5 6/12 * 2/3" 
>>> re.findall('(-?\d+)\/(\d+)\s([+\-*/])\s(-?\d+)\/(\d+)',s) 
[('15', '9', '+', '-9', '5'), ('6', '12', '*', '2', '3')] 
+0

绝对做到了!这是一个很好的解释!谢谢,我学到了很多东西! – CodeSandwich

0

来标记基于一个正则表达式的字符串的一般方法是:

import re 

pattern = "\s*(\d+|[/+*-])" 

def tokens(x): 
    return [ m.group(1) for m in re.finditer(pattern, x) ] 

print tokens("9/4 + 6 ") 

注意事项:

  • 正则表达式以\s*开始,以传递任何初始空白。
  • 与令牌相匹配的正则表达式的部分封闭在parens中以形成捕获。
  • 不同的令牌模式在捕捉中被交替操作|分开。
  • 请小心使用\W,因为它也会匹配空格。
相关问题