gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:03:42 26 4
gpt4 key购买 nike

我需要一个正则表达式来提取不同字符串中 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com