2016-08-02 133 views
3

比方說,我們有一個字符串如何在多行字符串中捕獲特定字符和字符串之間的字符串? Python的

string="This is a test code [asdf -wer -a2 asdf] >(ascd asdfas -were)\ 

test \ 

(testing test) test >asdf \ 

     test" 

我需要獲得字符之間的字符串>和字符串「測試」。

我試圖

re.findall(r'>[^)](.*)test',string, re.MULTILINE) 

但是我得到

(ascd asdfas -were)\ test \ (testing test) test >asdf. 

不過,我需要:

(ascd asdfas -were)\ 

asdf 

我怎樣才能得到那2個字符串?

+0

所以,我試圖修復你的代碼塊,你能確認它們是否符合你的意圖嗎? – jedwards

+0

謝謝。這是我想要的 – Sam

+1

這裏有一個偉大的正則表達式生成器幫助您測試https://regex101.com/#python – ti7

回答

2

什麼:

import re 

s="""This is a test code [asdf -wer -a2 asdf] >(ascd asdfas -were) 
test 
(testing test) test >asdf 
test""" 

print(re.findall(r'>(.*?)\btest\b', s, re.DOTALL)) 

輸出:

['(ascd asdfas -were)\n', 'asdf\n'] 

只有這種模式有些有趣的部分是:

  • .*?,其中?使得.* 「ungreedy」否則你會有一場單場比賽而不是兩場比賽。
  • 使用\btest\b作爲「結束」標識符(請參閱下面的Jan的評論)而不是testWhere

    \b 匹配空字符串,但只在開頭或詞的末尾....

注意,可以閱讀了關於re.DOTALL,因爲我認爲那是真的你想要什麼。 DOTALL.字符包含換行符,而MULTILINE讓錨點(^,$)匹配行的開始和結束,而不是整個字符串。考慮到你不使用錨點,我認爲DOTALL更合適。

+1

非常感謝。這正是我所期待的。我也很欣賞這個解釋。我會盡快接受這個答案。 – Sam

+1

請注意,這將與'tester','testerfield','testman'中的'test'匹配(也就是你的想法) - 也應用單詞邊界:'\ btest \ b'。 – Jan

+0

@Jan,多數民衆贊成在一個好主意,將編輯。 – jedwards

相關問題