aspose file tools
The moose likes Java in General and the fly likes escape * w/ java.util.regex.Pattern 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 "escape * w/ java.util.regex.Pattern" Watch "escape * w/ java.util.regex.Pattern" New topic
Author

escape * w/ java.util.regex.Pattern

Roger Orange
Greenhorn

Joined: Jan 28, 2009
Posts: 7
I want to match start and end comment blocks in some sql files.

how would I compile a pattern that matches strings that contain '/*'

i.e. escape the asterisk so it is matched as a literal character??




John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Roger:

You can use a character class to encapsulate the offending asterisk:

Another way would be to use a double backslash to escape it.

John.
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
John de Michele wrote:Roger:

You can use a character class to encapsulate the offending asterisk:

Another way would be to use a double backslash to escape it.

John.


There's no need to put the slash inside a character class (or escape it). Also, you will probably need to change the PLUS into a STAR because /**/ is also a valid comment block. And by default, the DOT does not match new line characters, so enabling the DOT-ALL option (?s) would be wise as well. So, that would look like this:



Although parsing source files using regex may not be a wise idea: the substring "/*" may occur inside a string literal which will make the regex match too much.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Piet:

Yep, I was just demonstrating character classes. I guess I got a little 'character-class happy' . You are correct about the asterisk vs. the plus; I guess I didn't think about the empty (i.e., /**/) case.

John.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: escape * w/ java.util.regex.Pattern
 
Similar Threads
doubt in string.split method
d'bt REgarding Comment !!!!
case little strange !
ajax not working with jsp
Regex Help Needed