Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate perl split to python split

Tags:

python

regex

perl

In perl:

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

splits mystring after every K or R via the two concepts "split between every character" (=empty string) + "lookbehind". So the sequence AAAKBBBBR becomes (AAAK,BBBBR).

Whats the counterpart in python? I cant find a way because the empty string does not split between characters!

like image 548
user3182532 Avatar asked Aug 07 '26 23:08

user3182532


1 Answers

Do you really need a look around? This regular expression should do it [^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

In words: match zero or more characters that are not K/R that are followed by K/R.

You might want to use the + quantifier to match at least one or more instead of * for cases like:

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

To make the trailing [KR] optional you can use ?:

In [5]: s = 'AAAKBBBBRAAA'
In [6]: re.findall(r'[^KR]+[KR]?', s)
Out[6]: ['AAAK', 'BBBBR', 'AAA']
like image 102
Chris Seymour Avatar answered Aug 09 '26 11:08

Chris Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!