簡體   English   中英

將perl拆分為python拆分

[英]Translate perl split to python split

在perl中:

split(/(?<=[KR])/,$mystring)

通過兩個概念“在每個字符之間拆分”(=空字符串)+“lookbehind”,在每個K或R之后拆分mystring。 因此序列AAAKBBBBR變為(AAAK,BBBBR)。

什么是python的對手? 我找不到辦法,因為空字符串不會在字符之間分割!

你真的需要環顧四周嗎? 這個正則表達式應該這樣做[^KR]*[KR]

In [1]: import re                        # Import the regex library
In [2]: s = "AAAKBBBBR"                  # Define the input string
In [3]: re.findall(r'[^KR]*[KR]', s)     # Find all the matches in the string
Out[3]: ['AAAK', 'BBBBR']

Regexplanation:

[^KR] # ^ in character classes is negation so will match any character except K/R
*     # Quantifier used to match zero or more of the previous expression
[KR]  # Simple character class matching K/R

在單詞中: 匹配零個或多個非K / R后跟K / R的字符。

對於以下情況,您可能希望使用+量詞來匹配至少一個或多個而不是*

In [1]: import re    
In [2]: s = "KAAAKBBBBR"
In [3]: re.findall(r'[^KR]*[KR]', s)
Out[3]: ['K', 'AAAK', 'BBBBR']
In [4]: re.findall(r'[^KR]+[KR]', s)
Out[4]: ['AAAK', 'BBBBR']

要使尾隨[KR]可選,你可以使用?

In [5]: s = 'AAAKBBBBRAAA'
In [6]: re.findall(r'[^KR]+[KR]?', s)
Out[6]: ['AAAK', 'BBBBR', 'AAA']

暫無
暫無

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

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