RegExp in Java - ilya-khadykin/notes-outdated GitHub Wiki
Java provides two classes from java.util.regex
for working with Regular Expressions: Pattern
and Matcher
More details can be found in official documentation:
- https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
- https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html
Here is a simple example of how to use them in Java:
package ru.itandlife.test_regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Khadykin Ilya on 5/13/2016.
*/
public class RegexExample {
// String to be scanned to find the pattern.
private static String SAMPLE_TEXT = "Results <span>1-50</span> of <span>5828</span> (page 1/117)";
private static String REGEX_PATTERN = "(.+)(\\(page.+)(/.+)";
public static void main(String[] args) {
// Create a Pattern object
Pattern p = Pattern.compile(REGEX_PATTERN);
// Now create matcher object
Matcher m = p.matcher(SAMPLE_TEXT);
// Attempting to find compiled pattern in target String
if (m.matches()) {
System.out.println("Source Text: " + m.group(0));
System.out.println("Pattern: " + REGEX_PATTERN);
System.out.println("\nThere are " + m.groupCount() + " groups");
for (int i=1; i<=m.groupCount(); i++) {
System.out.println("Group Number: " + i);
System.out.println(m.group(i));
}
} else {
System.out.println("Nothing matches to your pattern");
}
// Now we can do other things with found matches
System.out.println(m.group(2).replaceAll("\\D", ""));
}
}