jon jon
jon jon

Reputation: 53

Python Regex and group function

Hi trying to separate each of the expressions from the colon. So want to obtain 'ss_vv', 'kk' and 'pp'. But the two print expressions below give me 'v' and 'k', so getting parts only of each string. Can anyone see what wrong here?

m0 = re.compile(r'([a-z]|_)+:([a-z]|_)+:([a-z]|_)+')
m1 = m0.search('ss_vv:kk:pp')
print m1.group(1)
print m1.group(2)

Upvotes: 0

Views: 685

Answers (3)

user6759906
user6759906

Reputation:

What are the other rules for the regular expression? based on your question, this regex would do:

m0 = re.compile(r'(.*):(.*):(.*)')
m1 = m0.search('ss_vv:kk:pp')
print m1.group(1)
print m1.group(2)

UPDATE: as mentioned by @Jan in the comments, for efficient and better use of regex, you can modify it as

regex = r'([^:]+):([^:]+):([^:]+)'
m0 = re.compile(regex)

output:

ss_vv
kk

or by just splitting the string:

string = 'ss_vv:kk:pp'
parts = string.split(':')

print parts

outputs: ['ss_vv', 'kk', 'pp']

Upvotes: 1

Dinesh Pundkar
Dinesh Pundkar

Reputation: 4196

No need to use regex for your case. You can just split on basis of ':' and get required output..

>>> a = 'ss_vv:kk:pp'
>>> b_list = a.split(':')
>>> b_list
['ss_vv', 'kk', 'pp']
>>>

Upvotes: 1

Nehal J Wani
Nehal J Wani

Reputation: 16629

In [52]: m0 = re.compile(r'([a-z|_]+):([a-z|_]+):([a-z|_]+)')

In [53]: m1 = m0.search('ss_vv:kk:pp')

In [54]: print m1.group(1)
ss_vv

In [55]: print m1.group(2)
kk

In [56]: print m1.group(3)
pp

What my regex does:

([a-z|_]+):([a-z|_]+):([a-z|_]+)

Regular expression visualization

Debuggex Demo

What your regex does:

([a-z]|_)+:([a-z]|_)+:([a-z]|_)+

Regular expression visualization

Debuggex Demo

Upvotes: 4

Related Questions