Python 基于正则表达式的字符串拆分
我有字符串格式的数学表达式。它只包含“+”或“-”运算符。我必须根据运算符拆分字符串Python 基于正则表达式的字符串拆分,python,regex,string,python-3.x,split,Python,Regex,String,Python 3.x,Split,我有字符串格式的数学表达式。它只包含“+”或“-”运算符。我必须根据运算符拆分字符串 expr = '1234 + 896 - 1207 + 1567 - 345' words = word.split('-\|+') print(words) 我尝试过这个方法,但它给出了原始字符串的原样。使用re.split在多个分隔符上拆分: import re word = '1234 + 896 - 1207 + 1567 - 345' words = re.split(r' - | \+ ', w
expr = '1234 + 896 - 1207 + 1567 - 345'
words = word.split('-\|+')
print(words)
我尝试过这个方法,但它给出了原始字符串的原样。使用
re.split
在多个分隔符上拆分:
import re
word = '1234 + 896 - 1207 + 1567 - 345'
words = re.split(r' - | \+ ', word)
print(words)
# ['1234 ', '896', '1207', '1567', '345']
如果要保留运算符,请使用组括号:
re.split(r"\s*([+-])\s*",expr)
Out: ['1234', '+', '896', '-', '1207', '+', '1567', '-', '345']
您的标题建议使用您自己的解决方案使用的正则表达式,这也是您返回相同字符串的原因: 已修复(但不是您想要的): 输出:
['1234 ', ' 896 ', ' 1207 ', ' 1567 ', ' 345']
['1234', '+', '896', '-', '1207/1567', '-', '345']
['1234', '896', '1207', '1567', '345'] # without numbers.append( c ) for c in ops
以下是不使用正则表达式的替代解决方案: 迭代字符串中的所有字符,如果是数字(没有空格和+-),则将其添加到临时列表中。如果是+或-将临时列表中的所有数字合并,并将其添加到结果列表中:
ops = set( "+-" )
expr = '1234 + 896 - 1207 / 1567 - 345'
# result list
numbers = []
# temporary list
num = []
for c in expr:
if c in ops:
numbers.append( ''.join(num))
numbers.append( c ) # comment this line if you want to loose operators
num = []
elif c != " ":
num.append(c)
if num:
numbers.append( ''.join(num))
print(numbers)
输出:
['1234 ', ' 896 ', ' 1207 ', ' 1567 ', ' 345']
['1234', '+', '896', '-', '1207/1567', '-', '345']
['1234', '896', '1207', '1567', '345'] # without numbers.append( c ) for c in ops
如果您确实需要使用正则表达式-为什么要使用该函数?