Match multiple words in any order via one regex

后端 未结 2 1639
自闭症患者
自闭症患者 2021-01-16 10:44

as stated in heading I want regex which will give me results in order based on my \'query\'.

line=\'VERSION=\"OTHER\" POWER=\"LOW\" FREQ=\"OFF\" MAXTUN=\"BLE         


        
相关标签:
2条回答
  • 2021-01-16 11:28

    You may leverage a non-capturing alternation group to match either VERSION or FREQ (optionally preceded with a word boundary, just check if it meets your requirements):

    \b(?:VERSION|FREQ)="(.*?)"
    

    See the regex demo

    Details

    • \b - a leading word boundary
    • (?:VERSION|FREQ) - either VERSION or FREQ
    • =" - a =" substring
    • (.*?) - Group 1 (the actual output of findall): any 0+ chars other than line break chars, as few as possible
    • " - a double quote.

    See the Python demo:

    import re
    line='VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'
    print(re.findall(r'\b(?:VERSION|FREQ)="(.*?)"', line))
    # => ['OTHER', 'OFF']
    

    A better idea, perhaps, is to capture key-value pairs and map them to a dictionary:

    import re
    line = 'VERSION="OTHER" POWER="LOW" FREQ="OFF" MAXTUN="BLER"'
    results = re.findall(r'(VERSION|FREQ)="(.*?)"', line)
    print(dict(results))
    # => {'FREQ': 'OFF', 'VERSION': 'OTHER'}
    

    See the Python demo.

    0 讨论(0)
  • 2021-01-16 11:39

    I'm afraid there is no way to match in the order you want using regex: you could execute the part before | first, and then the part after |. Or order the result afterwards.

    0 讨论(0)
提交回复
热议问题