基于正则表达式的字符串拆分

2024-05-13 21:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有字符串格式的数学表达式。它只包含“+”或“-”运算符。我必须根据运算符拆分字符串

expr = '1234 + 896 - 1207 + 1567 - 345'
words = word.split('-\|+')
print(words)

我试过这个,但它给原来的字符串,因为它是


Tags: 字符串表达式格式运算符数学wordsplitwords
3条回答

您的标题建议使用regex,您自己的解决方案使用string.split(),这也是您获得相同字符串的原因:

expr = '1234 + 896 - 1207 + 1567 - 345'
words = word.split('-\|+')  # splits only if ALL given characters are there 
print(words)

修正(但不是你想要的):

expr = '1234 -\|+ 896 -\|+ 1207 -\|+ 1567 -\|+ 345'
words = expr.split('-\|+')  
print(words)

输出:

['1234 ', ' 896 ', ' 1207 ', ' 1567 ', ' 345']

下面是一个不使用regex的替代解决方案:

迭代字符串中的所有字符,如果它是一个数字(没有空格和+-),则将其添加到临时列表中。如果是+或-连接临时列表中的所有数字并将其添加到结果列表:

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'] # without numbers.append( c ) for c in ops

如果要保留运算符,请使用组括号:

re.split(r"\s*([+-])\s*",expr)
Out: ['1234', '+', '896', '-', '1207', '+', '1567', '-', '345']

使用re.split拆分多个分隔符:

import re

word = '1234 + 896 - 1207 + 1567 - 345'
words = re.split(r' - | \+ ', word)
print(words)

# ['1234 ', '896', '1207', '1567', '345']

相关问题 更多 >