python替換指定字元

2021-06-20 23:31:46 字數 1254 閱讀 3343

有如下一段文字,要求將中括號後的第乙個分號;替換為換行符

[souma, kousaku;kanda, fumie;masuko, takayoshi] tokyo univ agr, fac bioind, abashiri, hokkaido 0992493, japan;[wang, peng] jgfdsa univ, coll ansfdm sci & vet med, chanfdsn 130023, jfdsn, peoples r china;[igarashi, hiroaki] hokuren federat agr cooperat assoc, obihiro branch off, obihiro, hokkaido, japan

思路,用正規表示式定位分號位置,用subn替換

a="[souma, kousaku;kanda, fumie;masuko, takayoshi] tokyo univ agr, fac bioind, abashiri, hokkaido 0992493, japan;[wang, peng] jgfdsa univ, coll ansfdm sci & vet med, chanfdsn 130023, jfdsn, peoples r china;[igarashi, hiroaki] hokuren federat agr cooperat assoc, obihiro branch off, obihiro, hokkaido, japan"

pattern=re.compile(r"(\[.*?\].*?)(;)(?=\[)")

pattern.subn(r'\1\n',a)[0]

輸出結果:

'[souma, kousaku;kanda, fumie;masuko, takayoshi] tokyo univ agr, fac bioind, abashiri, hokkaido 0992493, japan\n[wang, peng] jgfdsa univ, coll ansfdm sci & vet med, chanfdsn 130023, jfdsn, peoples r china\n[igarashi, hiroaki] hokuren federat agr cooperat assoc, obihiro branch off, obihiro, hokkaido, japan'

注意:1、在.*後加?禁用貪婪模式,否則只能搜尋到最後乙個分號

2、subn的意思是將匹配到的串用正規表示式r'\1\n'替換,其中\1即pattern中第乙個分組,第二個分組是分號用\n替代

python版本2.7.3

JS正則替換指定字元

定義和用法 replace 方法用於在字串中用一些字元替換另一些字元,或替換乙個與正規表示式匹配的子串。語法 stringobject.replace regexp,replacement 引數 描述regexp 必需。規定了要替換的模式的 regexp 物件。請注意,如果該值是乙個字串,則將它作為...

python修改替換檔案每行的指定字元

簡單的修改檔案裡的字串 有個朋友經常要修改一大堆檔案裡指定字元的批量修改 所以寫了下面一段 filename modified.txt hand str input 字首詞 strip endwith str input 字尾詞 strip change str input 要修改的整數初始值 fi...

Python 替換檔案中指定字串

1 將替換後的內容儲存到新檔案中 import sys import re f1 open home wuzz 11.txt r f2 open home wuzz 12.txt w str1 r hello str2 r hi for ss in f1.readlines tt re.sub st...