简体   繁体   中英

Split a line with matching regex special characters

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM