Regex 提取子字符串的正则表达式是什么?

Regex 提取子字符串的正则表达式是什么?,regex,python-3.x,Regex,Python 3.x,我需要一个正则表达式来提取不同字符串中的vector\u name的值。我尝试了以下方法,但未能成功 进口稀土 # 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 = "li

我需要一个正则表达式来提取不同字符串中的
vector\u name
的值。我尝试了以下方法,但未能成功

进口稀土

# 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

有人知道什么是正确的正则表达式吗?

[^/]+
模式贪婪地匹配一个或多个字符,而不是
/

您可以限制要匹配的字符,例如,与
\w+
匹配,以匹配一个或多个单词字符(即字母、数字、下划线):

:


请尝试
r'vector\u name=(\w+)
太好了,谢谢Wikitor,这很好我不好,我没有提到
vector\u name
可以用相同的值在相同的字符串中复制。所以我只需要抓住它一次。因为在这个例子中,它没有正确返回值
ipdb>zz'options={},params={vector\u name=get\u x,default\u like\u count=2,setting\u id=1200,system=0 back options={},params={vector\u name=get\u x,default\u like\u count=2,setting\u id=1200,system=0 back'ipdb>re.search(r'vector\u name=([^/]+),',,zz)。组(1)'get\u x,default\u like\u count=2,setting\u id=1200,system=0,back选项,{={vector_name=get_x,默认_like_count=2,设置_id=1200'
@JVK,因此,
re.search
是您需要的,因为它提取第一个匹配项。请查看仅获取
get_x
值的位置。
r'vector_name=(\w+)'
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']