• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Pattern to match multiline strings

 
Ranch Hand
Posts: 50
Hibernate Eclipse IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
I am writing a program to delete all the comments from a given java file.

I was able to remove the single line comments using pattern - Pattern p= Pattern.compile("//(.)*");

But matching multiline comments is getting trickier.
I am using - Pattern p= Pattern.compile("/\\*.*\\*/", Pattern.DOTALL); - Basically match anything between /* and */ and include new lines.

But If I have something like below, it is matching this entire thing as a single match and I am losing the code between the comments.
/**
*comment1
*/
codeline1
line2
/**
*comment2
*/

Could some one help me how to rewrite this pattern so that I dont delete the code between the comments?

Thanks in advance.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Srikanth Madasu wrote:
I am writing a program to delete all the comments from a given java file.

I was able to remove the single line comments using pattern - Pattern p= Pattern.compile("//(.)*");

But matching multiline comments is getting trickier.
I am using - Pattern p= Pattern.compile("/\\*.*\\*/", Pattern.DOTALL); - Basically match anything between /* and */ and include new lines.

But If I have something like below, it is matching this entire thing as a single match and I am losing the code between the comments.
/**
*comment1
*/
codeline1
line2
/**
*comment2
*/

Could some one help me how to rewrite this pattern so that I dont delete the code between the comments?




The easiest option is to use a reluctant qualifier.

Henry
 
Srikanth Madasu
Ranch Hand
Posts: 50
Hibernate Eclipse IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry.

It worked. Just changed pattern to include reluctant quantifier "?" .

Thanks!
 
reply
    Bookmark Topic Watch Topic
  • New Topic