将perl的split转换为python的split

3 投票
1 回答
599 浏览
提问于 2025-04-18 10:46

在Perl语言中:

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

这个代码会在每个K或R后面把字符串分开,使用了两个概念:“在每个字符之间分割”(也就是用空字符串)加上“向后查看”。所以像AAA K BBBBB R这样的字符串会变成(AAAK, BBBBR)。

那么在Python中怎么做呢?我找不到方法,因为空字符串不能在字符之间分割!

1 个回答

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']

正则表达式解释:

[^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']

撰写回答