[英]How to get the index of remaining string index after regexp in Python?
我已經在 python 中使用正則表達式獲得了匹配的字符串,如下所示。
import re
matches = re.finditer(r'<\S+?>',' Hi <a> This is </a> an example! ')
for match in matches:
print(
"matched string: '%s', start index: %s, end index: %s"
% (match.group(0), match.span(0)[0], match.span(0)[1])
)
導致:
matched string: '<a>', start index: 4, end index: 7
matched string: '</a>', start index: 16, end index: 20
現在我想獲得剩余的字符串索引,例如:
[0,4],[7,16],[20,33]
這樣的事情應該給你預期的輸出:
import re
str = ' Hi <a> This is </a> an example! '
matches = re.finditer(r'<\S+?>',str)
start = 0
output = []
for match in matches:
output.append([start,match.start()])
start = match.end()
output.append([start,len(str)])
print(output)
[[0, 4], [7, 16], [20, 33]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.