我需要一个正则表达式来提取不同字符串中vector_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+限制要匹配的字符,以匹配1个或多个单词字符(即字母,数字,下划线):

r'vector_name=(\w+)'

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']

关于regex - 提取子字符串的正则表达式是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54640390/

10-12 04:35
查看更多