Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Regex Python thay thế string.replace: xóa thẻ dạng <[số>

Dùng re.sub() để thay thế tất cả các chuỗi khớp mẫu bằng chuỗi rỗng, đạt hiệu quả tương tự string.replace() nhưng mạnh hơn nhờ regex.

Ví dụ: Xóa thẻ <[số> và </[số>

import re
line = ('this is a text with<[2> in between and then there are instances '
        '... where the<[43> number ranges from 0-99. '
        'and there are many other lines in the text files '
        'with<[7> such tags ')
line = re.sub(r"<\/?\[\d+>", "", line)
print(line)

Kết quả

this is a text with in between and then there are instances ... where the number ranges from 0-99.and there are many other lines in the text files with such tags

Giải thích pattern: <\/?\[\d+> khớp cả thẻ mở <[số> và thẻ đóng </[số>.