This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Java in General and the fly likes Pattern matching problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Pattern matching problem" Watch "Pattern matching problem" New topic
Author

Pattern matching problem

Rahul Ba
Ranch Hand

Joined: Oct 01, 2008
Posts: 205
I am trying to retrive the body contents and file tag conetents if any.

String str = "<body>1</body><file>myFile1</file><body>2</body><body>3</body><file>myFile2</file>";
Pattern pattern = Pattern.compile("<body>(.*?)</body><file>(.*?)</file>");
Matcher matcher = pattern.matcher(str);
while(matcher.find()) {
System.out.println("BValue:"+matcher.group(1));
System.out.println("FValue:"+matcher.group(2));
}

I am getting the output in this way
BValue:1
FValue:myFile1
BValue:2</body><body>3
FValue:myFile2

See, mu BValue is not coming properly, I want output in following way...I know this is not in proper pattern..but still can we achieve this output?


BValue:1
FValue:myFile1
BValue:2
BValue:3
FValue:myFile2

Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
I am not a fan of engaging the heavy regex engine when string positions would do just fine, as they do in your case.

You could rewrite your program using code.indexOf("<body") etc. and loop over all occurances.


JDBCSupport - An easy to use, light-weight JDBC framework -
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

The problem is that your regular expression requires a <file> to come after an <body>. That's why the non-greedy .*? will match "2</body><body>3". To prevent this, make the <file> optional.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
GeeCON Prague 2014
 
subject: Pattern matching problem