Friday, 22 April 2016

How to use Pattern and Matcher classes ?


Pattern and Matcher classes

Compile a regular expression using regex expression
Pattern myPattern = Pattern.compile("regex");

Split the subject string using the compiled regular expression
myPattern.split("subject")
Exactly same result as : "subject".split("regex")  
but, faster since the regex was already compiled.

Create a Matcher object from the Pattern object
Matcher myMatcher = Pattern.matcher("subject")

* The advantage of having two separate classes is that you can create many Matcher objects from a single Pattern object, and thus apply the regular expression to many subject strings simultaneously.

Find the next matches of regex in the subject string
myMatcher.find()
The Matcher is automatically reset to the start of the string when find() fails.

Replace the matched string with new string
myMatcher.replaceAll("replacement")
Exactly same results as : "subject".replaceAll("regex", "replacement") 
but, faster due to pre-compilation.


Matching special characters
Backslash
In regex, the backslash is also an escape character. The regular expression \\ matches a single backslash.
"\\\\" will match single backslash. 
Here : \\ for regex and \\ for Java backslash symbol.

Word
Regex \w matches a word character. As a Java string, this is written as \\w.

Dollar sign
Same as this, a single dollar sign in the replacement text becomes "\\$" when written as a literal Java string.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.