简体   繁体   中英

RegEx: Comma separated complex groups

Assume I have a comma separated line:

aa,bb,cc

I can regex this using (not really ok because this also matches ,aa but that is not the question here) :

(<my pattern>)?(,<my pattern>)*

Eg

([a-zA-Z]*)?(,[a-zA-Z]*)*

NOW, assume that <my pattern> is very long and complex , it would be nice if I could say something like:

(<my pattern>)?(,<repeat previous/named group>)*  

Is there a way to say to repeat a certain group (name) (in Python 3.5)

恐怕这种语法语法在正则表达式中不存在,但是考虑到python使用字符串作为正则表达式,您可以简单地使用字符串格式来减少代码:

re.findall('({0})?(,{0})*'.format(<your_pattern>), <some_string>)

There are regex engines that support this kind of backreference, but Python's regex engine does not.

However, just because the regex engine doesn't have builtin support for this doesn't mean we can't build a regex pattern that achieves our goal. All we have to do is change the , in the regex - instead of looking for a comma, we want to allow a comma or the start of the string:

((?:,|^)[a-zA-Z]*)*

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