简体   繁体   中英

Regex captured groups with positive lookbehind (python)

How is it possible to combine a captured group with positive lookbehinds?

I want to match the following examples:

DS
DS,x=y
Some DS,key=value
Some DS test,key=value&key2=value2
Some DS test,key=value&key2=value2|key3=value3

I came up with the following regex for matching everything but the comma:

^(?P<ds_title>[\w \|\-\=\&æøåÆØÅ]+)(?P<filters>[\w \|\-\=\&æøåÆØÅ]+)?$

I've figured out, that the regex I would need to insert is:

(?<=\,)

But I cannot figure out where to insert it. No matter where I insert it, it seems to break. Does anyone know how this can be done correctly?

Aren't you overthinking this?

^(?P<ds_title>[^,]+)(?:,(?P<filters>.+))?$

Why not just allow any string, rather than limiting it to your list?


In fact, why use a regex at all?

parts = data.split(',', 2)
if len(parts) == 1:
    title, = parts
else:
    title, filters = parts

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