Chris Willis
Chris Willis

Reputation: 65

Python Regex to Extract Word From Multiline String

How would I extract the serial number from the following python string:

blah:              asdf
blah:              asdf
Serial Number:     1234ABCD
blah               asdf
blah               asdf

I have tried the following, but it doesn't appear to be working:

serial_num = re.search("^Serial Number:\s*(\w*)$", serial_num, re.MULTILINE)

Upvotes: 0

Views: 2002

Answers (1)

m87
m87

Reputation: 4523

You may perhaps use the following regex ...

Serial\sNumber.*?(?=\w)(\w+)

see regex demo

python ( demo )

import re

s = """
blah:              asdf
blah:              asdf
Serial Number:     1234ABCD
blah               asdf
blah               asdf
"""
r = r"Serial\sNumber.*?(?=\w)(\w+)"
m = re.findall(r, s)
print(m)[0]

Upvotes: 2

Related Questions