![](/img/trans.png)
[英]Find all occurrences of regex pattern, but ignore occurrences that contain another pattern
[英]How to find all occurrences of a pattern and their indices in Python
是否有一種pythonian或簡寫方式來從字符串及其索引中獲取所有模式的出現? 我可以寫一個方法來做到這一點,我只是想知道是否有一個超短的單行或者什么:)
python re
模塊來救援。
>>> import re
>>> [x.start() for x in re.finditer('foo', 'foo foo foo foo')]
[0, 4, 8, 12]
re.finditer
返回一個生成器 ,這意味着不是使用list-comprehensions而是可以在for-loop
使用,這將更有效的內存。
您可以擴展它以獲得給定文本中的模式范圍。 即開始和結束指數。
>>> [x.span() for x in re.finditer('foo', 'foo foo foo foo')]
[(0, 3), (4, 7), (8, 11), (12, 15)]
不是Python真棒:)不能阻止自己引用XKCD ,downvotes或沒有downvotes ......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.