[英]how to use python regex find matched string?
對於字符串"//div[@id~'objectnavigator-card-list']//li[@class~'outbound-alert-settings']"
"@..'...'"
"//div[@id~'objectnavigator-card-list']//li[@class~'outbound-alert-settings']"
,我想查找"@..'...'"
例如"@id~'objectnavigator-card-list'"
或"@class~'outbound-alert-settings'"
。 但是當我使用正則表達式((@.+)\\~(\\'.*?\\'))
,它會找到"@id~'objectnavigator-card-list']//li[@class~'outbound-alert-settings'"
。 那么如何修改正則表達式以成功找到字符串呢?
在內括號上使用非捕獲的,非貪婪的修飾符,並搜索不作為終止符的字符,例如:
re.findall(r"((?:@[^\~]+)\~(?:\'[^\]]*?\'))", test)
在測試字符串上返回:
["@id~'objectnavigator-card-list'", "@class~'outbound-alert-settings'"]
將您想匹配的字符限制在引號之間,以使其與引號不匹配:
>>> re.findall(r'@[a-z]+~\'[-a-z]*\'', x)
我發現僅查找我知道將要出現在匹配部分中的字符比從更寬容的匹配中省略字符要容易得多。
對於當前測試字符串的輸入,您可以嘗試以下模式:
import re
a = "//div[@id~'objectnavigator-card-list']//li[@class~'outbound-alert-settings']"
# find everything which begins by '@' and neglect ']'
regex = re.compile(r'(@[^\]]+)')
strings = re.findall(regex, a)
# Or simply:
# strings = re.findall('(@[^\\]]+)', a)
print(strings)
輸出:
["@id~'objectnavigator-card-list'", "@class~'outbound-alert-settings'"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.