spritecodej
spritecodej

Reputation: 459

extract several value using Regular Expression in Python

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

Answers (5)

Mushif Ali Nawaz
Mushif Ali Nawaz

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

Rakesh
Rakesh

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

Veera Balla Deva
Veera Balla Deva

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

Nathan
Nathan

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

Austin
Austin

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

Related Questions