• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pattern to match multiline strings

 
Srikanth Madasu
Ranch Hand
Posts: 48
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • 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.
 
Henry Wong
author
Marshal
Pie
Posts: 21185
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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: 48
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry.

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

Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic