| Author |
Regular Expression - Match till a given string
|
Jayesh Netravali
Greenhorn
Joined: May 07, 2003
Posts: 12
|
|
Hi, I am in need of a regular expression which will match a string till a given string. For eg consider that I have the following text in a file - <File start> ... DEFINE QLOCAL(TEST.QUEUE1) + DEFBIND(NOTFIXED) + DESCR('Test Queue') + BOQNAME(TEST.BACKOUT) + BOTHRESH(2) DEFINE NAMELIST(TEST.NAMELIST) + NAMES(TEST1) ... <File end> I want to get the first definition in this file i.e. from DEFINE QLOCAL(... till ...BOTHRESH(2) When I use the regular expression "DEFINE QLOCAL\\([A-Za-z0-9.\\)]*" with the Pattern class in java.util.regex I get only 'DEFINE QLOCAL(TEST.QUEUE1)' as expected But I need the text till the next occurrence of the string "DEFINE" i.e. till "BOTHRESH(2)" What should be the regular expression that I need to use?
|
 |
Scott Selikoff
Saloon Keeper
Joined: Oct 23, 2005
Posts: 3652
|
|
Can we see some example code of what you're working with? If you're searching a file line by line (and not as one large string), I'd recommend just searching using String.startsWith() on each line. Alternatively, if you have each line of the file in a large string, then just mark where you've read the first occurence then only search on the remainder of the string.
|
My Blog: Down Home Country Coding with Scott Selikoff
|
 |
Michael Swierczek
Ranch Hand
Joined: Oct 07, 2005
Posts: 95
|
|
Jayesh Netravali, I believe the regular expression pattern you want is ("(?s)DEFINE QLOCAL(.*?)DEFINE"). - I'm no expert, I've just played with regular expressions a little. The (?s) regular expression flag tells Java to treat the entire input String as one line. Otherwise, it will only search for matches on a given line. It will not be counted as one of the matcher groups. The (.*?) means match all characters in a non-greedy fashion. So it will stop the first time it sees another DEFINE. So if you have an input string named contents, and the string above is in a string named matchpattern, Matcher matcher = Pattern.compile(matchpattern).matcher(contents); The Matcher class returns its results from a match as groups. Group(0) is the whole match. Group 1 is the first section in parenthesis. Group 2 is the second parenthetical group. And so forth. So to print out the defined function: if (matcher.find() == true) { System.out.println("DEFINE QLOCAL" + matcher.group(1)); } Does that help? [ January 05, 2006: Message edited by: Michael Swierczek ]
|
 |
 |
|
|
subject: Regular Expression - Match till a given string
|
|
|