Java Search Pattern Part 2

  1. Create a pattern string with a regular expression.
  2. Compile it so it can be used multiple times.
  3. apply matches(0 function.
  4. if matches() functions return true then a patter is a match
  5. if matches() return false then pattern does not exist inside the search text.
static void simpleMatchesTest(final String patternString, final String text) {
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
System.out.printf("%s found is : %s\n", patternString, matcher.matches());
}
static void simpleMatcherTest(final String patternString, final String text) {

Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
int count = 0;
while (matcher.find()) {
count++;
System.out.printf("found: %d : %d - %d %n", count, matcher.start(), matcher.end());
}
}
Here is the output:
Task :MatcherTest.main()
.*exam-system.* found is : true
.*test-system.* found is : false
found: 1 : 31 - 35
found: 2 : 50 - 54
static void simpleGroupTest(final String patternString, final String text) {

Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.printf("found: %s %s %n", matcher.group(1), matcher.group(2));
}
}
public static void main(String[] args) {
String text = "https://www.onlinetestplus.com/exam-system/";
String patternString = ".*exam-system.*";
simpleMatchesTest(patternString, text);
patternString = ".*test-system.*";
simpleMatchesTest(patternString, text);

text = "https://www.onlinetestplus.com/exam-system/online-exam-software/";
patternString = "exam";
simpleMatcherTest(patternString, text);
patternString = "(exam)-(.+?/)";
simpleGroupTest(patternString, text);
}

--

--

--

Specialist in Cloud Native development

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

An interesting tool or technology I encountered in preparation for Andela’s Bootcamp.

ROAMEXT — Roam Research Extended: A Little Piece of Code With Mighty Power

Colored blocks

Implementing an elevator | Unity

Site Realiability Engineer

Site Realiability Engineer

Coroutines With Unity!

7 Top Programming Languages To Learn Before The End of the 2020s

Of Software and Strive at Strava

PowerShell — Let’s make it personal

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
BIS

BIS

Specialist in Cloud Native development

More from Medium

Java Date Time APIs

TIL 0621 Head First Java ch4 — How Objects Behave

Do you know, how JVM runs our “Hello World!” Java program?

What is JVM, JRE & JDK