[英]How to match regex in python?
describe aws_security_group({:group_id=>"sg-ezsrzerzer", :vpc_id=>"vpc-zfds54zef4s"}) do
我嘗試從中過濾掉sg-ezsrzerzer
(所以我想過濾 start sg-
直到雙引號)。 我正在使用 python
我目前有:
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)
output 是
['sg-ezsrzerzer", :vpc_id=>"vpc-zfds54zef4s"}) do']
我怎樣才能得到['sg-ezsrzerzer']
?
如果目標是在您的示例中格式化的給定字符串中提取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)
Output
['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)
Output
'sg-ezsrzerzer'
如果您決定使用re.search
,您會發現如果在您的輸入字符串中找不到匹配項,它會返回None
,如果存在則返回一個re.Match
object - 因此使用if
語句並調用s.group()
來提取如果在上面的示例中存在匹配字符串。
模式\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))
Output
['sg-ezsrzerzer']
匹配直到第一個單詞邊界與\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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.