I'm having trouble writing a regular expression that matches the text I need it to. Let me give an example to express my trouble. Suppose I have the following text:
I want to find the line "find me" and match everything up from it to the nearest "else if(condition)". There can be anything at all between them, including newline characters. I tried the following regular expression:
m/else\sif\(condition\)[\s\S]*?find\sme/
Unfortunately the above regular expression does not do what I want. It finds the first "else if(condition)" and selects everything down to the first "find me" despite the nongreedy asterisk. Is there a way to match the "find me" first and then search up for for the "else if(condition)"?
Note: I know the above example doesn't make any sense code-wise. It's not the text I'm trying to match, but it's much less complicated and expresses what I'm trying to accomplish better.
I like utility cgrep for situations like this. It allows one to specify conveniently a regular expression for the previous and succeeding boundaries -- "windows":
#!/usr/bin/env bash
# @(#) s1 Demonstrate previous boundary match with cgrep.
# http://www.bell-labs.com/project/wwexptools/cgrep/
echo
set +o nounset
LC_ALL=C ; LANG=C ; export LC_ALL LANG
echo "Environment: LC_ALL = $LC_ALL, LANG = $LANG"
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version "=o" $(_eat $0 $1)
set -o nounset
echo
FILE=${1-data1}
echo " Data file $FILE:"
cat $FILE
echo
echo " Results:"
cgrep -D -w "else if" "find me" $FILE
exit 0
producong:
% ./s1
Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution : Debian GNU/Linux 5.0
GNU bash 3.2.39
Data file data1:
if(condition)
multiline
statement
else if(condition)
multiline
statement
else if(condition)
multiline
statement
else if(condition)
multiline
statement
else if(condition)
multiline
statement
find me
else if(condition)
multiline
statement
Results:
else if(condition)
multiline
statement
find me
You will need to obtain, compile, and make available cgrep. See the URL mentioned in the script for that.