Search code examples
pythonregexregex-negationregex-group

regex only start with value1 without value1\nvalue2


New in regex,trying catch files on server where string start with only value1 but if we have in file value1 and next string value2 we don't add it in output

keyword = re.findall(r'^process.args=spring.*?xml(?!process.script=true)', line,re.S)

Any advices please?

need output like this :

xxxx xxx xxx xxx
process.args=spring.xxxx.xml
process.script=true
xxxx xxx xxx xxx\n```

output after regex : None

and 

```xx xx xxx xxx xxx
xxxx xxx xxx xxx
process.args=spring.xxxx.xml
xxxx xxx xxx xxx```

output after regex : process.args=spring.xxxx.xml


Solution

  • In your pattern you use the negative lookahead xml(?!process right after xml. But as it is at the end of the string, you could prepend matching a newline before \r?\nprocess

    Note that if .xml is at the end of the string, you don't have to make the dot non greedy and that you have to escape the dot to match it literally.

    You could also add a word boundary after true to make sure it is not part of a longer word.

    ^process\.args=spring.*\.xml(?!\r?\nprocess\.script=true\b)
    

    Regex demo | Python demo

    For example

    import re
    
    regex = r"^process\.args=spring.*\.xml(?!\r?\nprocess\.script=true\b)"
    
    line = ("xxxx xxx xxx xxx\n"
        "process.args=spring.xxxx.xml\n"
        "process.script=true\n"
        "xxxx xxx xxx xxx\n\n\n"
        "xx xx xxx xxx xxx\n"
        "xxxx xxx xxx xxx\n"
        "process.args=spring.xxxx.xml\n"
        "xxxx xxx xxx xxx")
    
    res = re.findall(regex, line, re.MULTILINE)
    print(res)
    

    Output

    ['process.args=spring.xxxx.xml']