簡體   English   中英

用逗號和空格或空格分割字符串

[英]Split string by comma and space or space

我有兩個示例字符串,我想用“、”(如果存在)或“”來分割它們。

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

拆分應該只執行一次以恢復兩條信息:

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

For ">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,]+(.*)

請參閱正則表達式演示 詳情

  • ^ - 字符串的開頭
  • ((?=.*,)[^,]+|\S+) - 第 1 組:如果有 a ,則在除換行符之外的任何零個或多個字符之后盡可能多地匹配除換行符之外的一個或多個字符, , 或匹配一個或多個非空白字符
  • [\s,]+ - 零個或多個逗號/空格
  • (.*) - 第 2 組:除換行符之外的零個或多個字符盡可能多

請參閱Python 演示

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}'")

Output:

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

[不滿足問題]你只需要檢查字符串中是否有逗號

def split(n):
    if ',' in n:
        return n.split(', ')
    return n.split(' ')

您可以在第一次出現時拆分,或者在沒有出現的空格上拆分,使用交替向右:

, | (?!.*?, )

模式匹配:

  • ,匹配,
  • | 或者
  • (?.?*,, )負前瞻,斷言右邊不是,

請參閱Python 演示正則表達式演示

例子

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))

Output

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM