python
  • regex
  • 2013-05-13 48 views 1 likes 
    1

    所以我有這樣的:正則表達式多取代

    z='===hello 
    there===, 
    how are ===you===?' 
    

    而且我想:

    z='<b>hello 
    there<\b>, 
    how are <b>you<\b>?' 
    

    我試着這樣做:

    z = re.sub(r"\={3}([^\$]+)\={3}", r"<b> \\1 </b>", z, re.M) 
    

    和它的作品的那種,但我取而代之:

    z='<b>hello 
    there===, 
    how are ===you<\b>?' 
    

    我還是一個新手,但我相信它是^$,它使它匹配字符串的開頭和結尾。那麼如何改變它,使它與中間的相匹配?從蟒蛇DOC

    +0

    使用4位或 - 縮進代碼 – jamylak 2013-05-13 09:06:39

    回答

    2
    re.sub(r"\={3}([^\$]+?)\={3}", r"<b> \\1 </b>", z, re.M) 
    

    複製:

    *?, +?, ?? The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.

    +2

    請解釋爲什麼這個修復有機磷農藥的問題,所以他在知道未來。 (這是因爲+?是懶惰的並且匹配儘可能少的字符,所以它停在第一個'<\b>'而不是最後一個'<\b>') – Patashu 2013-05-13 06:38:58

    +0

    哦,我明白了。它的工作!它也解決了我非常感謝的另一個問題! – user2270501 2013-05-13 06:46:40

    相關問題