• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Pattern matching problem

 
Ranch Hand
Posts: 215
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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

 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Sheriff
Posts: 22701
129
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Whatever. Here's a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic