Forums Register Login

Regular Expression - Match till a given string

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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 ]
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 2043 times.
Similar Threads
extract html tags from....
Regular Expressions on a .csv file
mock question
A small problem in replaceAll
help please
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 02:44:31.