我有以下表达式,我需要能够将这些表达式解析为不同的标记:
"a=b+c" -> a b + c
"a=5+c" -> a 5 + c
"a=c*50" -> a c * 50
"a=50%50" -> a 50 % 50
"a=c-x[20]" -> a c - x[20]
"a=x[3]+50" -> a x[3] + 50
"a=b--c" -> a b - -c我使用了这帮大忙,但是我只能在一个例子中应用正则表达式,而不是所有的正则表达式。例如,下面的代码只适用于"a=b+c“、"a=c-50”,但如果我将它们转换为"a=c-50,“a=b+c,则不会:
#!/usr/bin/python
# URL that generated this code:
# http://txt2re.com/index-python.php3?s=%22a=b%2bc%22,%20%22a=c-50%22&-32&-34&25&-35&-33&36&27&5
import re
txt='"a=b+c", "a=c-50"'
re1='.*?' # Non-greedy match on filler
re2='(a)' # Any Single Character 1
re3='.*?' # Non-greedy match on filler
re4='(b)' # Any Single Character 2
re5='(.)' # Any Single Character 3
re6='(c)' # Any Single Character 4
re7='.*?' # Non-greedy match on filler
re8='(a)' # Any Single Character 5
re9='.*?' # Non-greedy match on filler
re10='.' # Uninteresting: c
re11='.*?' # Non-greedy match on filler
re12='(.)' # Any Single Character 6
re13='(.)' # Any Single Character 7
re14='(\\d+)' # Integer Number 1
rg = re.compile(re1+re2+re3+re4+re5+re6+re7+re8+re9+re10+re11+re12+re13+re14,re.IGNORECASE|re.DOTALL)
m = rg.search(txt)
if m:
c1=m.group(1)
c2=m.group(2)
c3=m.group(3)
c4=m.group(4)
c5=m.group(5)
c6=m.group(6)
c7=m.group(7)
int1=m.group(8)
print("("+c1+")"+"("+c2+")"+"("+c3+")"+"("+c4+")"+"("+c5+")"+"("+c6+")"+"("+c7+")"+"("+int1+")"+"\n")发布于 2018-08-07 08:10:32
尝试使用re.split(),它会在运算符的基础上拆分你的方程。例如:
text = 'a=x[3]+50'
pattern = r'([\=\+\-\%\*])'
result = re.split(pattern, text)输出:
['a', '=', 'x[3]', '+', '50']https://stackoverflow.com/questions/51721595
复制相似问题