Reputation: 459
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.
Upvotes: 0
Views: 72
Reputation: 3866
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
Upvotes: 0
Reputation: 82815
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']
Upvotes: 1
Reputation: 788
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']
Upvotes: 1
Reputation: 3648
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))
Upvotes: 1
Reputation: 26057
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']
Upvotes: 1