describe aws_security_group({:group_id=>"sg-ezsrzerzer", :vpc_id=>"vpc-zfds54zef4s"}) do我尝试从它中过滤sg-ezsrzerzer (所以我想在start sg-上过滤直到双引号)。我在用蟒蛇
我目前有:
import re
a = 'describe aws_security_group({:group_id=>"sg-ezsrzerzer", :vpc_id=>"vpc-zfds54zef4s"}) do'
test = re.findall(r'\bsg-.*\b', a)
print(test)输出是
['sg-ezsrzerzer", :vpc_id=>"vpc-zfds54zef4s"}) do']我怎样才能得到['sg-ezsrzerzer']
发布于 2021-06-04 15:59:51
如果目标是提取给定字符串中的group_id值(如您的示例中所示),则模式group_id将很好地工作。
(?<=group_id=\>")在要匹配的字符串之前查找子字符串group_id=>"。
.+?匹配任何字符懒惰中的一个或多个字符。
(?=\")在匹配之后查找字符" (实际上使表达式.+匹配除结束"以外的任何字符)。
如果您只想提取group_id从sg-开始的子字符串,那么您可以简单地将其添加到模式的匹配部分,如下所示:(?<=group_id=\>")sg\-.+?(?=\")
import re
s = 'describe aws_security_group({:group_id=>"sg-ezsrzerzer", :vpc_id=>"vpc-zfds54zef4s"}) do'
results = re.findall('(?<=group_id=\>").+?(?=\")', s)
print(results)输出
['sg-ezsrzerzer']当然,您也可以使用re.search而不是re.findall来查找与给定字符串中的上述模式匹配的子字符串的第一个实例,这取决于您的用例。
import re
s = 'describe aws_security_group({:group_id=>"sg-ezsrzerzer", :vpc_id=>"vpc-zfds54zef4s"}) do'
result = re.search('(?<=group_id=\>").+?(?=\")', s)
if result:
result = result.group()
print(result)输出
'sg-ezsrzerzer'如果您决定使用re.search,您将发现如果输入字符串中没有找到匹配项,则返回None,如果有匹配项,则返回re.Match对象--因此,在上面的示例中,将调用if语句并调用s.group()提取匹配的字符串。
发布于 2021-06-04 20:23:12
模式\bsg-.*\b匹配太多,因为.*将匹配到字符串的末尾,然后返回到第一个单词边界,这是在o和字符串结束之后。
如果您使用的是re.findall,您也可以使用一个捕获组而不是查找器,并且结果中将显示组值。
:group_id=>"(sg-[^"\r\n]+)"模式匹配:
:group_id=>"匹配(sg-[^"\r\n]+)捕获组1匹配sg-和1+乘以除"或换行符以外的任何字符"匹配双引号例如
import re
pattern = r':group_id=>"(sg-[^"\r\n]+)"'
s = "describe aws_security_group({:group_id=>\"sg-ezsrzerzer\", :vpc_id=>\"vpc-zfds54zef4s\"}) do"
print(re.findall(pattern, s))输出
['sg-ezsrzerzer']发布于 2021-06-04 20:49:48
匹配直到第一个单词边界与\w+
import re
a = 'describe aws_security_group({:group_id=>"sg-ezsrzerzer", :vpc_id=>"vpc-zfds54zef4s"}) do'
test = re.findall(r'\bsg-\w+', a)
print(test[0])见Python证明。
解释
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
sg- 'sg-'
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))结果:g-ezsrzerzer
https://stackoverflow.com/questions/67839237
复制相似问题