0

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

3
  • Try this simple regex '([^']+)'.*?(\d+) Commented Nov 9, 2015 at 13:23
  • 1
    Use raw strings: re.compile(r"(.+')(?P<request_name>.*)(' took )(?P<request_time>\d+)(.*)") Commented Nov 9, 2015 at 13:26
  • Your code works for me. reg.match() returns a match object with the named groups matching exactly what you want. (also tested on regex101.com/#python) Commented Nov 9, 2015 at 13:28

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.