Python Forum

Full Version: Need help to extract particular string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I want to extract particular string in a file.suppose file contains the following string.

INFO 2019-02-19 20:59:56,178 - Process Start time : 2019-02-19 20:55:09.778793
INFO 2019-02-19 20:59:56,178 - Process End time : 2019-02-19 20:59:56.178893

Output should be like as below.

Output:
Process Start time : 2019-02-19 20:55:09.778793 Process End time : 2019-02-19 20:59:56.178893
I tried to achieve the output using below but not succeeded.

import re
    re.match("(.*)Process Start time(.*)", line):
        c= line.split("-")[3]
        print(c)
Could you please help me in advance
I think you need an if before the second line. But that won't get the end time. You probably just want to check for 'Process'. In fact, a regular expression is overkill for this. You can just use if 'Process' in line:.
Hi,

It is not working which i tried as below

import re
re.match("(.*)Process Start time(.*)", line):
c= line.split("-")[3]
print©


output:
======
Process Start time : 2019


In date format hyphen(-) is exists so that is the reason it is extracting only year.

Thanks in advance
Use Code tag as you have gotten info about.

If doing it with regex it could be like this.
import re

data = '''\
INFO 2019-02-19 20:59:56,178 - Process Start time : 2019-02-19 20:55:09.778793
INFO 2019-02-19 20:59:56,178 - Process End time : 2019-02-19 20:59:56.178893'''

>>> r = re.findall(r"P.*", data)
>>> r
['Process Start time : 2019-02-19 20:55:09.778793',
 'Process End time : 2019-02-19 20:59:56.178893']

>>> print('\n'.join(r))
Process Start time : 2019-02-19 20:55:09.778793
Process End time : 2019-02-19 20:59:56.178893

# Without regex
>>> for line in data.split('\n'):
...     line.split(' - ')[::-2]
    
['Process Start time : 2019-02-19 20:55:09.778793']
['Process End time : 2019-02-19 20:59:56.178893']