Regex Pattern to Match, Excluding when… / Except between

前端 未结 6 887
别跟我提以往
别跟我提以往 2020-11-21 05:07

--Edit-- The current answers have some useful ideas but I want something more complete that I can 100% understand and reuse; that\'s why I set a bounty. Als

6条回答
  •  时光取名叫无心
    2020-11-21 05:23

    Same as @zx81's (*SKIP)(*F) but with using a negative lookahead assertion.

    (?m)(?:if\(.*?\/\/endif|\([^()]*\))(*SKIP)(*F)|\b\d+\b(?!.*\.$)
    

    DEMO

    In python, i would do easily like this,

    import re
    string = """cat 123 sat.
    I like 000 not (456) though 111 is fine
    222 if(  //endif if(cat==789 stuff  //endif   333"""
    for line in string.split('\n'):                                  # Split the input according to the `\n` character and then iterate over the parts.
        if not line.endswith('.'):                                   # Don't consider the part which ends with a dot.
            for i in re.split(r'\([^()]*\)|if\(.*?//endif', line):   # Again split the part by brackets or if condition which endswith `//endif` and then iterate over the inner parts.
                for j in re.findall(r'\b\d+\b', i):                  # Then find all the numbers which are present inside the inner parts and then loop through the fetched numbers.
                    print(j)                                         # Prints the number one ny one.
    

    Output:

    000
    111
    222
    333
    

提交回复
热议问题