Home > Blockchain >  How to use regular expression to split string and put splitting char in the previous part?
How to use regular expression to split string and put splitting char in the previous part?

Time:05-07

str1 = "2000a200b20c"

I want to use regular expression to split this string and I hope the result like,

["2000a","200b","20c"]

I tried to

import re
print(re.split(r'([a-z])',str1)

but it shows,

["2000","a","200","b","20","c",""]

I have two question,how to combine the character with previous one and why there is always a blank in end of list?

CodePudding user response:

I would use a regex find all approach here:

str1 = "2000a200b20c"
parts = re.findall(r'\d [a-z] ', str1, flags=re.I)
print(parts)  # ['2000a', '200b', '20c']

CodePudding user response:

If you want to use split, you can use the following:

import re
str1 = "2000a200b20c"
re.split( '(?<=[a-z])(?=\d)' , str1)

This says that you need to split at a point that is

  1. preceded by a character '(?<=[a-z])', and
  2. followed by a number '(?=\d)'

You should review the look-ahead and look-back parts of regular expressions.

  • Related