2017-02-13 137 views
1

我想從字符串在兩個給定的其他字符串之間的文本中獲取字符串 - 但這兩個後面的字符串都是用正則表達式部分定義的也。Python正則表達式:搜索兩個表達式之間的表達式(也是正則表達式)

所以,從下面幾行:

ALPHA101BETAsomething1GAMMA532DELTA 
ALPHA231BETAsomething2GAMMA555DELTA 
ALPHA341BETAagainsomethingsomethingGAMMA998DELTA 

我想獲得如下:

something1 
something2 
againsomething 

我在這裏的問題是,我無法定義的開啓和關閉的表達,使這些是再加上一個三位數表達式再加上一些東西。

到目前爲止,我試過,但這個失敗:

re.findall("ALPHA(?:\d\.){3}BETA(.*?)GAMMA(?:\d\.){3}DELTA", pagetext) 

我怎麼能指示解析器給定的正則表達式匹配組不是想要的結果,但開/關字符串的一部分?

+0

是他們的任何線分隔符? –

+1

你期望與「(?:\ d \。){3}」匹配嗎?輸入字符串中是否有文字點?也許你需要的只是['(?s)ALPHA \ d {3} BETA(。*?)GAMMA \ d {3} DELTA'](https://regex101.com/r/XUaVfi/1)?另請參閱[Python演示](https://ideone.com/ecZPuA)。 –

回答

0

我修改了正則表達式,現在它適用於我。 您可以使用re.compile,re.search和re.group讓您尋找特定的字符串:

import re 
REGEX = re.compile(r'ALPHA(\d){3}BETA(.*?)GAMMA(\d){3}DELTA') 
# The next part is all about how your pagetext is formatted. 
# if you have newlines in the pagetext: 
for line in pagetext.split('\n'): 
    result = re.search(REGEX, line) 
    your_desired_str = result.group(2) 

# if you just want to read the text line by line from a file: 
with open(yourfile) as infile: 
    for line in infile: 
     result = re.search(REGEX, line) 
     your_desired_str = result.group(2) 
0

這會爲你工作: -

import re 
text ='ALPHA101BETAsomething1GAMMA532DELTA\nALPHA231BETAsomething2GAMMA555DELTA\nALPHA341BETAagainsomethingsomethingGAMMA998DELTA' 


for line in text.split('\n'): 

    print re.findall(r'ALPHA+\d+BETA(.*?)GAMMA+\d+DELTA',line)[0] 
+0

這是否適合你? –