Regular expression to replace multiple lines that match a pattern
If I have a bunch of text like this
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
Is there a Regular Expression I could use in the Find/Replace feature of my text editor (Jedit) to identify all of the lines that begin with the word Expropriations
and end with a closing parenthesis and then put those lines inside square brackets so that they look like this:
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
The tricky thing is that the closing parenthesis could fall at the end of the same line as the word 'Expropriations' or at the end of the next line. (there might even be more than one line before the parentheses are closed)
You can match:
^(Expropriations[\d\D]*?\))
and replace it with:
[$1]
\d\D
matches any single char including the newline.
If you can specify regex options, try to activate "single line". That way, regex does not care about line breaks.
Does Jedit support search and replace with multiline regular expressions?
Here is how to achieve this using a python script.
Main point is to set the DOTALL ('s'
) and MULTILINE ('m'
) flags of the regex.
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
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
精彩评论