1

How to use python regular expression to extract data from the below two string

TASK000123-Tomcat server hosted on tbu.test1 is down-P1 --In Progress

TASK000123-Tomcat server hosted on tbu.test1 is down-P1 --Completed

I need the following csv file from this:

Format: TaskID,Priority,Status

TASK000123,P1,In Progress

TASK000123,P2,Completed

How can I do this? Thanks for helping me out

2 Answers 2

2

This is one approach using a simple iteration.

Ex:

s = """TASK000123-Tomcat server hosted on tbu.test1 is down-P1 --In Progress
TASK000123-Tomcat server hosted on tbu.test1 is down-P1 --Completed"""

result = [["TaskID","Priority","Status"]]

for i in s.splitlines():
    val = i.split("-")                          #Split by '-'
    result.append([val[0], val[2], val[-1]])
print(result)

Output:

[['TaskID', 'Priority', 'Status'],
 ['TASK000123', 'P1 ', 'In Progress'],
 ['TASK000123', 'P1 ', 'Completed']]
Sign up to request clarification or add additional context in comments.

2 Comments

Too fast for me I was about to post the same thing :)
Thanks you so much. Can you tell me how to put the result in a csv file?
2

Here in an option using re.findall:

input = "TASK000123-Tomcat server hosted on tbu.test1 is down-P1 --In Progress\nTASK000123-Tomcat server hosted on tbu.test1 is down-P1 --Completed"
results = re.findall(r"(TASK\d+).*?-(P\d+) --(.*)(?=\n|$)", input)
print(results)

[('TASK000123', 'P1', 'In Progress'), ('TASK000123', 'P1', 'Completed')]

Note that DOT ALL mode should not be necessary here, because we never need .* to match across newlines. Also, the above seems to work without using MULTILINE mode as well.

9 Comments

Nice, still wished I knew regex like some of you do
@Jaba To really get proficient with regex, you're going to have to just start using it a lot. There is barrier of entry, with a pot of gold on the other side of the mountain.
@TimBiegeleisen Nice! The most accurate definition of Regex ;)
By the time I'm proficient as you I'll likely have the same rep as you do now and you double :D
Maybe...but there is a phenomenon/problem on the site, with major contributors quitting around 200K. Once you get the second T-shirt, I guess what is the point of continuing :P
|

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.