Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Regular Expression - Match till a given string  RSS feed

Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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>
DESCR('Test Queue') +

<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?
Posts: 4096
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Ranch Hand
Posts: 125
Clojure Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jayesh Netravali,

I believe the regular expression pattern you want is
- 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" +;

Does that help?
[ January 05, 2006: Message edited by: Michael Swierczek ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!