【问题标题】:Split string by comma and space or space用逗号和空格或空格分割字符串
【发布时间】:2022-01-08 18:02:30
【问题描述】:

我有两个示例字符串,我想用“、”(如果 , 存在)或“”来分割它们。

x = ">Keratyna 5, egzon 2, Homo sapiens"
y = ">101m_A mol:protein length:154  MYOGLOBIN"

应该只执行一次拆分以恢复两条信息:

id, description = re.split(pattern, string, maxsplit=1)

对于">Keratyna 5, egzon 2, Homo sapiens" -> [">Keratyna 5", "egzon 2, Homo sapiens"]

对于">101m_A mol:protein length:154 MYOGLOBIN" -> [">101m_A", "mol:protein length:154 MYOGLOBIN"]

我想出了以下模式: ",\\s+|\\s+", ",\\s+|^,\\s+", "[,]\\s+|[^,]\\s+", 但这些都不起作用。

我做的解决方案是使用异常:

try:
    id, description = re.split(",\s+", description, maxsplit=1)
except ValueError:
    id, description = re.split("\s+", description, maxsplit=1)

但老实说,我讨厌这种解决方法。我还没有找到任何合适的正则表达式模式。我该怎么做?

【问题讨论】:

  • 你试过,?\s+吗?
  • 请不要用垃圾邮件标记不相关的语言标签。这是一种快速积累反对票的方法
  • 是的,我试过了,?\s+,不幸的是不起作用。
  • 使用.split(",") 以逗号分隔字符串。然后使用.strip(" ") 清理生成的字符串以删除不需要的空格。
  • @HovercraftFullOfEels 抱歉,我想如果我的问题实际上是大多数编程语言都相同的正则表达式模式,我不仅可以使用 python 标签。感谢您指出这一点。

标签: python regex


【解决方案1】:

您可以在第一次出现, 时进行拆分,也可以在右侧没有出现, 的空格上使用交替进行拆分:

, | (?!.*?, )

模式匹配:

  • , 匹配,
  • |或者
  • (?!.*?, ) 负前瞻,断言右边不是,

查看Python demoregex demo

例子

import re

strings = [
    ">Keratyna 5, egzon 2, Homo sapiens",
    ">101m_A mol:protein length:154  MYOGLOBIN"
]

for s in strings:
    print(re.split(r", | (?!.*?, )", s, maxsplit=1))

输出

['>Keratyna 5', 'egzon 2, Homo sapiens']
['>101m_A', 'mol:protein length:154  MYOGLOBIN']

【讨论】:

    【解决方案2】:

    你可以使用

    ^((?=.*,)[^,]+|\S+)[\s,]+(.*)
    

    请参阅regex demo详情

    • ^ - 字符串开头
    • ((?=.*,)[^,]+|\S+) - 第 1 组:如果在除换行符之外的任何零个或多个字符之后有一个 ,,则尽可能匹配除 , 之外的一个或多个字符,或匹配一个或多个非空白字符字符
    • [\s,]+ - 零个或多个逗号/空格
    • (.*) - 第 2 组:除换行符之外的零个或多个字符尽可能多

    Python demo

    import re
    pattern = re.compile( r'^((?=.*,)[^,]+|\S+)[\s,]+(.*)' )
    texts = [">Keratyna 5, egzon 2, Homo sapiens", ">101m_A mol:protein length:154  MYOGLOBIN"]
    for text in texts:
        m = pattern.search(text)
        if m:
            id, description = m.groups()
            print(f"ID: '{id}', DESCRIPTION: '{description}'")
    

    输出:

    ID: '>Keratyna 5', DESCRIPTION: 'egzon 2, Homo sapiens'
    ID: '>101m_A', DESCRIPTION: 'mol:protein length:154  MYOGLOBIN'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 2018-03-22
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多