Eduardo
Eduardo

Reputation: 7141

Python Regex to extract variable

I am trying to extract 2 variables from a string in the following form

2015-11-07 10:04:30,855 INFO - RequestTimeLogger.logRequestTime(11) | Request to 'Get Cases (Between Dates)' took 514ms

I am trying to extract Get Cases (Between Dates) and the response time 514

I have tried the following using Python 2.7.6

reg = re.compile("(.+')(?P<request_name>.*)(' took )(?P<request_time>\d+)(.*)")
reg.match(mystringabove)

which returns false... What am I doing wrong?


The request name is always within quotes like 'something' and can be any character that isn't a quote The request time is always before ms

Upvotes: 0

Views: 80

Answers (2)

hjpotter92
hjpotter92

Reputation: 80639

Use raw string for the pattern (r"" format):

import re
p = re.compile(r".+'(?P<request_name>[^']*)' took (?P<request_time>\d+)ms")
test_str = "2015-11-07 10:04:30,855 INFO - RequestTimeLogger.logRequestTime(11) | Request to 'Get Cases (Between Dates)' took 514ms\n"
g = p.match(test_str).groupdict()

Upvotes: 1

SirParselot
SirParselot

Reputation: 2700

You can use search instead of match so you don't have to match the entire string.

import re
s="2015-11-07 10:04:30,855 INFO - RequestTimeLogger.logRequestTime(11) | Request to 'Get Cases (Between Dates)' took 514ms"

mat = re.search(r'Request to \'(.*)\' took (.*)ms',s)
if mat:
    print mat.group(1) + ' ' + mat.group(2)

Get Cases (Between Dates) 514

Upvotes: 1

Related Questions