在perl:
split(/(?<=[KR])/,$mystring)
通过两个概念“在每个字符之间拆分”(=空字符串)+“lookbehind”,在每个K或R之后拆分mystring。因此序列AAAKBBBBR变为(AAAK,BBBBR)。
什么是python中的对手?我找不到办法,因为空字符串不会在字符之间分开!
答案 0 :(得分:4)
[^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']