在Perl中:
split(/(?<=[KR])/,$mystring)
通过“在每个字符之间分割”(=空字符串)+“向后查找”的两个概念,将我的字符串在每个K或R之后分割。因此,序列AAAKBBBBR成为(AAAK,BBBR)。
在python中有什么对应的方法?我找不到方法,因为空字符串不能在字符之间分割!
在Perl中:
split(/(?<=[KR])/,$mystring)
通过“在每个字符之间分割”(=空字符串)+“向后查找”的两个概念,将我的字符串在每个K或R之后分割。因此,序列AAAKBBBBR成为(AAAK,BBBR)。
在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']
正则表达式解释:
[^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
+
量词,而不是*
。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']
perl
那样的本地正则表达式字符串,但在底层它使用的是libpcre
(与perl兼容的正则表达式),因此任何使用perl正则表达式的功能都可以从Python中完成,您只需要使用函数https://docs.python.org/2/library/re.html - Chris Seymour\
时,它不会阻止正则表达式函数正确解释正则表达式。 - Chris Seymour+
而不是 *
- Chris Seymour