【问题标题】:String split based on regular expressions基于正则表达式的字符串拆分
【发布时间】:2018-11-03 16:52:22
【问题描述】:

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

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

我已经尝试过了,但它给出了原始字符串。

【问题讨论】:

  • 如果您确实需要使用正则表达式 - 为什么要使用 string.split() 函数?

标签: python regex string python-3.x split


【解决方案1】:

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

import re

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您的标题建议使用正则表达式,您自己的解决方案使用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']
      

      这是一个不使用正则表达式的替代解决方案:

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

      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
      

      【讨论】:

        猜你喜欢
        • 2010-10-16
        • 2021-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-04
        相关资源
        最近更新 更多