简体   繁体   English

如何使用正则表达式查找字符超过 1 次?

[英]How do I use regular expressions to find a character more than 1 time?

import re
palabra="hola mundo"
caracter="o"
buscacaracter=(re.search(caracter,palabra))
print(buscacaracter)

So in this code it search until the first "o" is found but it doesn't count the last "o".所以在这段代码中,它搜索直到找到第一个“o”,但不计算最后一个“o”。

Is there a way to find every "o"?有没有办法找到每个“o”?

This happens with these methods as well:这些方法也会发生这种情况:

print(buscacaracter.start())
print(buscacaracter.end())
print(buscacaracter.span())

And when I use this method:当我使用这种方法时:

(re.findall(caracter,palabra))

it doesn't return the positions of the "o", just the number of them.它不返回“o”的位置,只返回它们的数量。

If you just want the index of each caracter it is faster, easier to use enumerate :如果你只想要每个caracter的索引,它会更快,更容易使用enumerate

palabra="hola mundo"
caracter="o"
>>> [i for i,c in enumerate(palabra) if c==caracter]
[1, 9]

If you want a regex, use finditer which return a match object which contains the index:如果你想要一个正则表达式,使用finditer返回一个包含索引的匹配对象

>>> [m.span()[0] for m in re.finditer(rf'{caracter}', palabra)]
[1, 9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM