簡體   English   中英

替換兩個特定字符之間所有出現的字符

[英]Replace All occurrences of character between two specific characters

我正在嘗試替換兩個已知字符( § )之間的所有逗號

我的測試字符串: '§Rd, Vasai - East, Thane§'

預期輸出: '§Rd; Vasai - East; Thane§' '§Rd; Vasai - East; Thane§'

我設法使用以下方法刪除了一個事件:

re.sub(r'(§[^§\r\n]*),([^§\r\n]*§)', r"\1;\2", '§Rd, Vasai - East, Thane§') 

但這又返回了: §Rd, Vasai - East; Thane§ §Rd, Vasai - East; Thane§

我們可以使用re.sub以及一個用分號替換逗號的回調函數來處理此問題:

def repl(m):
    str = m.group(0)
    return str.replace(",", ";")

inp = "Hello World blah, blah, §Rd, Vasai - East, Thane§ also Goodbye, world!"
print(inp)
print re.sub('§.*?§', repl, inp)

打印:

Hello World blah, blah, §Rd, Vasai - East, Thane§ also Goodbye, world!
Hello World blah, blah, §Rd; Vasai - East; Thane§ also Goodbye, world!

這里的想法是匹配以§開頭和結尾的每個字符串,然后有選擇地對該字符串進行另一個替換,以用分號替換逗號。 我假設§始終會保持打開和關閉狀態,否則,如果最后一個§可能懸而未決,您將可以接受。

這個表達,

(?<=^§|,)[^,§\r\n]*(?=§$|,)

使用re.findall可能也可以:

import re

matches = re.findall(r'(?<=^§|,)[^,§\r\n]*(?=§$|,)', "§Rd, Vasai - East, Thane§")
length = len(matches)
output = '§'
for i in range(length):
    if i == length - 1:
        output += str(matches[i]) + '§'
    else:   
        output += str(matches[i]) + ';'

print(output)

產量

§Rd; Vasai - East; Thane§

如果您想瀏覽/簡化/修改該表達式,請在regex101.com的右上方面板中進行說明 如果願意,您還可以在此鏈接中觀看,它將如何與某些示例輸入匹配。


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM