Search code examples
pythonregexregex-lookarounds

How to apply regex after applying lookarounds?



I have txt files which has data something like this:
file 1
var field = "123456";

file 2

var field = abdxg@% "345789";

So I used regex expression:

(?<=var fhID).*(?=;)


This returns: = "123456" in file 1 and = abdxg@% "345789" in file 2.
Now, I would like a single regex expression that would be able to extract only digits from the string after matching with lookarounds, i.e after modifying my current regex expression I should get 123456 in file 1 and 345789 in file 2.


Solution

  • You may use this regex and get matching digits in a capture group:

    (?<=var field)[^;\d]*(\d+)[^;]*(?=;)
    

    RegEx Demo

    btw it should be field in lookbehind instead of fhID.

    RegEx Details:

    • (?<=var field): Lookbehind to assert that we have var field before the current position
    • [^;\d]*: Match 0 or more of any characters that are not ; and digit
    • (\d+): Match 1+ digits in capture group #1
    • [^;]*: Match 0 or more of any characters that is not ;
    • (?=;): Positive lookahead to assert that we have a ; ahead of the current position