【问题标题】:I want to split the string with if it satisfies some conditions in python如果它满足python中的某些条件,我想拆分字符串
【发布时间】:2020-10-19 03:05:18
【问题描述】:
my_str = 'According to the teacher, "He never believed what I said. He ran away." And I think he did indeed. I tried to find him, but I could not.'

结果应该是:

['According to the teacher, "He never believed what I said. He ran away." And I think he did indeed.', 'I tried to find him, but I could not.']

在这个字符串中,我想用 .(dot) 分割它 但是,如果 .(dot) 在 " "(quotation) 中,我不想拆分它

我该如何使用re.split()?

【问题讨论】:

    标签: python regex string split


    【解决方案1】:

    考虑使用.findall,与:

    (?:[^."]+"[^"]+")*[^."]+\.
    

    https://regex101.com/r/d400Ut/1

    • (?:[^."]+"[^"]+")* - 重复 0 次或更多次:
      • [^."]+ 非". 字符,后跟
      • "[^"]+" - 引号内的字符
    • [^."]+\. - 匹配非." 字符,后跟句点
    matches = re.findall(r'(?:[^."]+"[^"]+")*[^."]+\.', my_str)
    

    【讨论】:

      【解决方案2】:

      不幸的是,这里没有适用于所有字符串的答案。您所描述的逻辑类型需要的不仅仅是正则表达式所使用的“常规”语法。您必须创建自己的自定义逻辑,例如:

      def custom_split_string(s: str) -> List[str]:
          output = []
          in_quote = False
          word = []
          for ch in s:
              word.append(ch)
              if ch == "." and not in_quote:
                  output.append(''.join(word))
                  word.clear()
              elif ch == '"':
                  in_quote = not in_quote  # assume no nested quotes
          return output
      
      my_str = 'According to the teacher, "He never believed what I said. He ran away." And I think he did indeed. I tried to find him, but I could not.'
      
      expected_output = ['According to the teacher, "He never believed what I said. He ran away." And I think he did indeed.', ' I tried to find him, but I could not.']
      
      assert custom_split_string(my_str) == expected_output
      

      【讨论】:

        猜你喜欢
        • 2016-08-22
        • 2019-03-16
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多