用正则表达式替换匹配模式的多行文本

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

棘手的问题在于右括号可能出现在与单词“征收”相同的行的末尾,也可能出现在下一行的末尾。(在右括号关闭之前可能有多行)

3个回答

2

您可以匹配以下内容:

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

并用以下内容替换它:
[$1]

\d\D 匹配任何单个字符,包括换行符。


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

猫坐在垫子上
[国际货币兑换征用(货币:美元,价值:50,000)]
猫坐在垫子上
[国际货币兑换征用(货币:日元)]
猫坐在垫子上

0
如果您可以指定正则表达式选项,请尝试激活“单行”。 这样,正则表达式就不会关心换行符。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接