[英]python find a pattern in string and enclose it in braces
我不是正則表達式的專家,並試圖做到以下幾點。
字符串“ s”可以包含模式16'h2020:16'h2F20
即十六進制范圍。 我需要將此匹配項括在方括號中並返回相同的字符串,即[16'h2020:16'h2F20]。
我這樣做是:
s = re.sub("\d+'h\d+:\d+'h\d+","[\d+'h\d+:\d+'h\d+]",s)
但是它不能按要求工作。 請幫忙。
在這里,您需要使用捕獲組 。
s = re.sub(r"(\d+'h\d+:\d+'h\d+F\d+)",r'[\1]',s)
例:
>>> import re
>>> s = "16'h2020:16'h2F20"
>>> re.sub(r"(\d+'h\d+:\d+'h\d+F\d+)",r'[\1]',s)
"[16'h2020:16'h2F20]"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.