簡體   English   中英

Python正則表達式取代了某些模式的位置

[英]Python regex substitute from some position of pattern

我有一個功能:

find = re.compile(ur"\s+(Word)\s+", flags = re.U)
text = find.sub('\1', text)

我想找到一些像這個“ Word ”(帶有前綴/后綴空格)的模式,並將其替換為“Word”(沒有那些空格)。 在ruby中我之前做過這樣的事情:

text.gsub('\s+(Word)\s+', '\1')

編輯:我的意思是我需要用新字符串或其他東西來改變這些空格取決於情況。

問題是Python將你的'\\ 1'解釋為一個特殊的反斜杠字符; 你需要使用一個原始字符串 ,這可以通過在字符串之前添加一個r來完成。 更改

find.sub('\1', text)

find.sub(r'\1', text)

例:

text = "Replace this Word "
find = re.compile(ur"\s+(Word)\s+", flags = re.U)
find.sub(r'\1', text)
# 'Replace thisWord'

試試這個:

regcom = re.compile('\s+Word\s+', re.UNICODE)
print regcom.sub(u'Word', u'This is a     Word     ')
u'This is aWord'

暫無
暫無

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

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