2010-03-02 71 views
5

如果我有這樣的正則表達式替換模式匹配的多行

The cat sat on the mat 
Expropriations for international monetary exchange (Currenncy: Dollars, 
                Value: 50,000) 
The cat sat on the mat 
Expropriations for international monetary exchange (Currenncy: Yen) 
The cat sat on the mat 

一堆文字是否有一個正則表達式,我可以在查找使用/替換我的文本編輯器的功能(JEDIT)識別所有的線是Expropriations一端與右括號然後把那些行方括號讓它們看起來像這裏面的開始:

The cat sat on the mat 
[Expropriations for international monetary exchange (Currenncy: Dollars, 
                Value: 50,000)] 
The cat sat on the mat 
[Expropriations for international monetary exchange (Currenncy: Yen)] 
The cat sat on the mat 

棘手的是,右括號可能會落在與「徵用」單詞相同的行末尾或下一行的末尾。 (在括號關閉之前甚至可能會有多行)

回答

2

可以匹配:

^(Expropriations[\d\D]*?\)) 

,取而代之的是:

[$1] 

\d\D任何單個字符,包括換行符相匹配。

0

如果您可以指定正則表達式選項,請嘗試激活「單行」。這樣,正則表達式並不關心換行符。

0

Jedit是否支持多行正則表達式的搜索和替換?

以下是如何使用python腳本實現此目的。

重點是設置正則表達式的DOTALL('s')和MULTILINE('m')標誌。

import re 
str = """The cat sat on the mat 
Expropriations for international monetary exchange (Currenncy: Dollars, 
                Value: 50,000) 
The cat sat on the mat 
Expropriations for international monetary exchange (Currenncy: Yen) 
The cat sat on the mat""" 

regex = re.compile(r'^(Expropriations.*?\))', re.S|re.M) 
replaced = re.sub(regex, '[\\1]', str) 
print replaced 

貓坐在墊子上
[國際貨幣交換徵用(Currenncy:美元,
值:50000)]
貓坐在墊子上
[徵用的國際貨幣交換(Currenncy:Yen)]
貓坐在墊子上