2010-03-02 100 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)]
猫坐在垫子上