Extract substring from string giving None

Viewed 54

I have a main string and I want to get a substring from it using regex. but its giving [] as result of findall

My mainString is

mainString="[31m\n[1m[31mError: [0m[0m[1mError import KeyPair: InvalidKeyPair.Duplicate: The keypair 'avtx-ctrl-key' already exists.\n\tstatus code: 400, request id: a56bb69b-0dc1-4c2f-a0c0-96d1be7c1efe[0m\n\n[0m[0m[0m\n[31m\n[1m[31mError: [0m[0m[1mError"

import re
start = re.escape("Error ")
end   = re.escape('[0m\n\n')
result = re.findall('%s(.*)%s' % (start, end), mainString)

and my desired output is

Error import KeyPair: InvalidKeyPair.Duplicate: The keypair 'avtx-ctrl-key' already exists.status code: 400, request id: a56bb69b-0dc1-4c2f-a0c0-96d1be7c1efe
1 Answers

You can use

(?s)Error:\s*(?:\[\d+m)+(.*?)(?=(?:\[\d+m)*\n\n)

See the regex demo. Details:

  • Error: - a literal string
  • \s* - 0+ whitespaces
  • (?:\[\d+m)+ - one or more repetitions of [, 1+ digits and m
  • (.*?) - Capturing group 1: any zero or more chars as few as possible
  • (?=(?:\[\d+m)*\n\n) - up to the first occurrence of 0+ sequences of [, 1+ digits + m and then a double newline char.

Python demo:

import re
mainString = "[31m\n[1m[31mError: [0m[0m[1mError import KeyPair: InvalidKeyPair.Duplicate: The keypair 'avtx-ctrl-key' already exists.\n\tstatus code: 400, request id: a56bb69b-0dc1-4c2f-a0c0-96d1be7c1efe[0m\n\n[0m[0m[0m\n[31m\n[1m[31mError: [0m[0m[1mError"
start = r"Error:\s*(?:\[\d+m)+"
end   = r"(?=(?:\[\d+m)*\n\n)"
result = re.findall('%s(.*?)%s' % (start, end), mainString, re.S)
print(result)

Output:

["Error import KeyPair: InvalidKeyPair.Duplicate: The keypair 'avtx-ctrl-key' already exists.\n\tstatus code: 400, request id: a56bb69b-0dc1-4c2f-a0c0-96d1be7c1efe"]
Related