JVK
JVK

Reputation: 3912

What would be the regular expression to extract substring?

I need to have a regular expression to extract the value of vector_name in different strings. I tried the followings, but could not get it to work.

import re

# I want to extract the value of vector_name using a regular expression

mystring1 = "options={}, params={vector_name=get_x, default_like_count=2, seeting_id=1200, system=0 back"
mystring2 = "literal options={}, params={setting_id=1200, seed_val=22, system=0, vector_name=get_Z foobar}"
mystring3 = "params={seed_rand=1200, seed_val=22, system=0, vector_name=corodinate2, tt=lly}"

# I have
re.search(r'vector_name=([^/]+),', mystring1).group(1)
# should give get_x

re.search(r'vector_name=([^/]+),', mystring2).group(1)
# should give get_Z

re.search(r'vector_name=([^/]+),', mystring3).group(1)
# should give corodinate2

Does anyone have any idea what would be the correct regex?

Upvotes: 3

Views: 29

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626853

The [^/]+ pattern matches one or more chars other than / greedily.

You may restrict the chars you want to match, say, with \w+, to match 1 or more word chars (i.e. letters, digits, underscores):

r'vector_name=(\w+)'

See the regex demo

Python demo:

import re
strs = ['options={}, params={vector_name=get_x, default_like_count=2, seeting_id=1200, system=0 back', 'literal options={}, params={setting_id=1200, seed_val=22, system=0, vector_name=get_Z foobar}', 'mystring3 = "params={seed_rand=1200, seed_val=22, system=0, vector_name=corodinate2, tt=lly}' ]
rx = re.compile(r'vector_name=(\w+)')
for s in strs:
    m = rx.search(s)
    if m:
        print(m.group(1))
# => ['get_x', 'get_Z', 'corodinate2']

Upvotes: 2

Related Questions