python - Split a line with matching regex special characters


Keywords:python 


Question: 

Currently I want to split a line with all the matching special characters of the regex. As it is hard to explain, here are a few examples:

('.+abcd[0-9]+\.mp3', 'Aabcd09.mp3') -> [ 'A', '09' ]

  • .+ is a special expression of the regex and this is the match that I want
  • [0-9]+ is another regex expression and I want what it matches too

('.+\..+_[0-9]+\.mp3', 'A.abcd_09.mp3') -> [ 'A', 'abcd', '09' ]

  • .+ is the first special expression of the regex, it matches A
  • .+ is the second special expression of the regex, it matches abcd
  • [0-9]+ is the third special expression of the regex, it matches 09

Do you know how to achieve this? I didn't find anything.


2 Answers: 

Looks like you need a so called tokenizer/lexer to parse a regular expression first. It will allow you to split a base regex on sub-expressions. Then just apply these sub-expressions to the original string and print out matches.

 

You can try this:

import re
s = ['Aabcd09.mp3', 'A.abcd_09.mp3']
new_s = [re.findall('(?<=^)[a-zA-Z]|(?<=\.)[a-zA-Z]+(?=_)|\d+(?=\.mp3)', i) for i in s]

Output:

[['A', '09'], ['A', 'abcd', '09']]