Kat*_*öhm 3 python regex python-re
在 Python 中使用正则表达式(库 re(仅)),我想创建一个函数,该函数给出字符串中所有前导 0 的位置。
例如,如果字符串是:我的房子有 01 个花园和 003 个房间。我希望函数返回 13、27 和 28。
我尝试过例如:
import re
string = "My house has 01 garden and 003 rooms."
pattern = "(0+)[1-9]\d*"
print(re.findall(pattern,string))
Run Code Online (Sandbox Code Playgroud)
显然,输出给了我匹配但没有位置......
您可以执行以下操作:
import re
text = "My house has 01 garden and 003 rooms."
pattern = re.compile(r"\b0+")
def leading_zeros_index(s: str) -> list:
return [i for m in pattern.finditer(s) for i in range(m.start(), m.end())]
print(leading_zeros_index(text))
Run Code Online (Sandbox Code Playgroud)
输出:
[13, 27, 28]
Run Code Online (Sandbox Code Playgroud)
基本上,您使用.finditer()来获取匹配对象,然后range()从匹配对象的.start()和创建一个对象.end()。
我用它\b0+作为图案。无需检查零后面的其他字符。\b是单词边界,这里的意思是,零应该在单词的开头。