Python Prog Python Prog - 4 months ago 8
Python Question

Regex failing to search a string

I am trying to do a regex search for

Location:
and get its location as follows,can anyone help to figure out why it doesn't print the location,expected output is shown below?

output = """
Build: BOOT.FAN.1.2-00179-M1234LAB-1
Location: \\location\builds678\INTEGRATION\BOOT.FAN.1.2-00179-M1234LAB-1
Comments: Build completed, labeled, and marked for retention.
Status: Approved [Approved for Testing]
BuildDate: 07/14/2016 17:54:54
"""
match=re.search(r'Location:\s*(\w*)',output)
print match.group(1)


EXPECTED OUTPUT:-

\\location\builds678\INTEGRATION\BOOT.FAN.1.2-00179-M1234LAB-1

Answer

Your string appears to contain special characters such as backspace (\b). You probably need to escape the backslashes, or use a raw string:

output = r"""
Build:          BOOT.FAN.1.2-00179-M1234LAB-1
Location:       \\location\builds678\INTEGRATION\BOOT.FAN.1.2-00179-M1234LAB-1
Comments:       Build completed, labeled, and marked for retention.
Status:         Approved  [Approved for Testing]
BuildDate:      07/14/2016 17:54:54
"""

Also there are a few other characters in the target string that will not be matched by just \w: \, . and - as per your example, possibly more. Try this pattern:

match = re.search(r'Location:\s+([\w\\\.-]+)',output)
print match.group(1)

Also you could simply match all characters to the end of the line:

match = re.search(r'Location:\s+(.+)',output)
print match.group(1)
Comments