[英]What is wrong with my attempt to do a string replace operation in Python?
[英]Python match and replace, what I do wrong?
我有用於匹配某些數據的reg exp( 在這里 ),現在我嘗試將所有匹配的數據替換為single :
characetr
test_str = u"THERE IS MY DATA"
p = re.compile(ur'[a-z]+([\n].*?<\/div>[\n ]+<div class="large-3 small-3 columns">[\n ]+)[a-z]+', re.M|re.I|re.SE)
print re.sub(p, r':/1',test_str)
我以其他幾種方式嘗試它,但它不能替換任何東西,或者不僅替換匹配的而且替換整個模式
1)這是反斜杠問題。
使用: print re.sub(p, r':\\1',test_str)
不print re.sub(p, r':/1',test_str)
。
2)您要用:\\1
替換所有模式,這意味着要用:
替換所有文本,然后是正則表達式中的第一組。
要僅替換文本中的第一個組,應在第一個和之后添加兩個組。 我希望這可以解決問題:
test_str = u"THERE IS MY DATA"
p = re.compile(ur'([a-z]+)([\n].*?<\/div>[\n ]+<div class="large-3 small-3 columns">[\n ]+)([a-z]+)', re.M|re.I|re.SE)
print re.sub(p, r'\1:\2\3',test_str)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.