2017-07-27 46 views
-1

今天我碰到這行代碼:無法理解re.findall模式語法

re.findall(r"#[^:]+:([^#]+)", str) 

我什麼模式findall功能正在尋找非常困惑。具體而言,r"#[^:]+:([^#]+)"是什麼意思?

我是一名高中生,所以如果你能用簡單的話來解釋它,那就太棒了!

+2

您應該開始閱讀[documentation](https://docs.python.org/2/library/re.html)並更新您的問題。 –

+0

作爲閱讀文檔的補充,您可以測試您的正則表達式並獲得關於它如何與[regex101.com](https://regex101.com)一起使用的解釋。 –

+0

我應該如何更新它? – Joe

回答

3

它的意思是:

 
# => matches the character # literally (case sensitive) 

[^:] => Match a single character that is not : 

+ => Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) and is applied to the [^:] 

: => matches the character : literally (case sensitive) 

([^#]+) => Capturing Group 

    [^#] => Match a single character not present in this list (match anything other than #) 

    + => Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) and is applied to [^#] 

並注意r字面意思是所要引用的字符串是raw文本,這意味着它裏面什麼沒有任何特殊含義的編譯器和你不必須逃避任何字符,甚至雙引號!

+0

這看起來像是對這個正則表達式的[regex101的解釋](https://regex101.com)的輕微修改。 OP將指出這一點會有所幫助。 –

+0

非常感謝 – Joe

+0

如果'str =「#個k點:816#個帶:52#個離子:8個''函數返回什麼?它會成爲「K點數:816」還是「816」? – Joe