Skip to content Skip to sidebar Skip to footer

Extract Number Between Text And | With RegEx Python

I want to extract the information between CVE and |, but only the first time that CVE appear in the txt. I have now the follow code: import re f = open ('/Users/anna/PycharmProjec

Solution 1:

What you might do is instead of matching \s at the start, match a whitespace character\s*zero or more times or assert the start of the string ^ and use search to find the first location where the regular expression pattern produces a match.

Then get the value from the capturing group:

mensaje = mensaje.replace("\n","")
regex = r"\s*CVE\s+([^|]*)"
matches = re.search(regex, mensaje)
if matches:
    print (matches.group(1).strip()) # 1381566

Demo


Solution 2:

A solution with split:

number = mensaje.split('CVE')[1].split('|')[0].strip()

Post a Comment for "Extract Number Between Text And | With RegEx Python"