This example demonstrates how we do regular expression in Java. The regular expression classes is in the java.uti.regex
package. The main class including the java.util.regex.Pattern
class and the java.util.regex.Matcher
class.
In this example we are only testing to match a string literal if it is exists in the following sentence, we are searching the word “lazy”.
package org.kodejava.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
/*
* To create a Pattern instance we must call the static method
* called compile() in the Pattern class. Pattern object is
* the compiled representation of a regular expression.
*/
Pattern pattern = Pattern.compile("lazy");
/*
* The Matcher class also doesn't have the public constructor
* so to create a matcher call the Pattern's class matcher()
* method. The Matcher object itself is the engine that match
* the input string against the provided pattern.
*/
String input = "The quick brown fox jumps over the lazy dog";
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(), matcher.end());
}
}
}
The output of the code snippet above is:
Text "lazy" found at 35 to 39.
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023