This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes Regular expression - capture groups Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Regular expression - capture groups" Watch "Regular expression - capture groups" New topic
Author

Regular expression - capture groups

Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 666
I have this code:


I expect it to print 2 lines:

start=4, end=8, match string=${abc}
start=15, end=19, match string=${xyz}

But it acctually prints only 1 line:

start=4, end=21, match string=${abc} 456 ${xyz}

Why?
Thanks.


BJ - SCJP and SCWCD
We love Java programming. It is contagious, very cool, and lot of fun. - Peter Coad, Java Design

Crazy Bikes created by m-Power
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24057
    
  13

Because regular expressions as "greedy" and match as much as possible by default. Your ".*" in the braces matches any character, so the first close brace is matched as part of the contents inside the braces.

There are a number of ways to fix this; one would be to use "[^}]*" instead of ".*".


[Jess in Action][AskingGoodQuestions]
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 666
Thanks.
"[^}]*" instead of ".*" fixed it.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Regular expression - capture groups
 
Similar Threads
questions regarding regular expressions
Complex regular expressions
Struggeling with regexp
Please help me check this regex
Regular expression pattern ${* }