Reputation: 33
I'm trying to split services' name and their status with Regex.
This works fine:
message = "svnserve is stopped"
match = re.search(r"(.*)\s+is\s+(\w*)", message)
print match.group(1),match.group(2)
# output=> svnserve stopped
but when I found line like this it doesn't work:
message = "openssh-daemon (pid 1982) is running"
match = re.search(r"(.*)\s+is\s+(\w*)", message)
print match.group(1),match.group(2)
# output => openssh-daemon (pid 1982) running
How I can remove the (pid 1982)
; I just want the name and the state.
Any help?
Upvotes: 1
Views: 1888
Reputation: 4080
re.search(r"(.*)\s+is\s+(\w*)",str)
This regex takes anything up to the first space as its first group, then matches the word "is" with an unspecified number of spaces on either side, then takes an alpha numeric character string after that as its next group. This second group includes spaces. A better strategy would be to take the first and last word, separated by spaces. Try
match = re.search(r"^([\S]+).*\s([\S]+)$",str)
Upvotes: 0
Reputation: 174696
You could use re.findall
function to do a global match. \S+
matches one or more non-space characters.
>>> m = re.findall(r'^\S+|\S+$', message)
>>> print(m[0],m[1])
svnserve stopped
>>> message = "openssh-daemon (pid 1982) is running"
>>> m = re.findall(r'^\S+|\S+$', message)
>>> print(m[0],m[1])
openssh-daemon running
OR
If you want to fed \s+is\s+
into your regex then try the below.
>>> message = "openssh-daemon (pid 1982) is running"
>>> m = re.search(r'^(\S+).*?\s+is\s+.*?(\S+)$', message)
>>> print(m.group(1),m.group(2))
openssh-daemon running
Or you could simply use re.search(r'^(\S+).*?(\S+)$', message)
Upvotes: 1
Reputation:
The service name will always be the first word in the string and its state will always be the last. So, you can simply split the string and grab these two items directly:
message = "svnserve is stopped"
match = message.split()
print match[0], match[-1]
Demo:
>>> message = "svnserve is stopped"
>>> match = message.split()
>>> print match[0], match[-1]
svnserve stopped
>>>
>>> message = "openssh-daemon (pid 1982) is running"
>>> match = message.split()
>>> print match[0], match[-1]
openssh-daemon running
>>>
Upvotes: 1