0

I want to extract several value using regular expression in python

The string is id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld

"NAA1, 4, WJQ, 13, HelloWorld" is the value what I want.

At first time, I tried like that

import re
msg = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld"
_id = re.search('id : (.*?),', msg)

But I want all value using just one re pattern matching.

2
  • You are searching for id specifically, but seem to want anywthing after a colon, and don't mind if you have priority or whatever before it. Commented Feb 21, 2018 at 13:25
  • 4
    Do you need regex? You could just split the text on the commas and colons, and trim the results. Commented Feb 21, 2018 at 13:25

5 Answers 5

1

Use:

import re
msg = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld"
print(re.findall(r' : ([^,]*)', msg))

Output:

['NAA1', '4', 'WJQ', '13', 'HelloWorld']
Sign up to request clarification or add additional context in comments.

Comments

1

The regex finds each of the strings afer ": " until a space is found. For this to work on the entire string a space should be added to the end of it.

import re
string = string + ' '
result = re.findall(': (.*?) ', string)
print(' '.join(result))

Comments

1
import re
STRING_ = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld"
re.findall(r':([\s\w\d]+)',STRING_)
>>>[' NAA1', ' 4', ' WJQ', ' 13', ' HelloWorld']

Comments

1

Without using regex:

a = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld"
print [i.split(":")[1].strip() for i in a.split(",")]

Output:

['NAA1', '4', 'WJQ', '13', 'HelloWorld']

Comments

0

It can be done without using regex:

msg = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld"
extracted_values = [value.split()[-1] for value in msg.split(", ")]
print(", ".join(extracted_values))

Output:

NAA1, 4, WJQ, 13, HelloWorld

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.