Pattern Matching in Java

Java pattern matching:

Let’s create an array with multiple names, and then use pattern matching to see which ones are valid. We’ll say a valid name is 2-10 characters long, and needs to be letters only. No numbers or other characters.

import java.util.regex.Pattern;

import java.util.regex.Matcher;

public class Main{

public static void main(String[] args){

String[] names = {“Robert”,

“asd75f”,

“aaaaaaaaaaaaaaa”,

“jennifer”,

“e”};

Pattern namePattern = Pattern.compile(“^[A-Za-z]{2,10}$”);

for (int i = 0; i < names.length; i++){

Matcher nameMatcher = namePattern.matcher(names[i]);

System.out.printf(“Name %d (%s) matches regex? %b\n”,

i, names[i], nameMatcher.matches());

}

}

}

← Previous | Next →

Java Topic List

Main Topic List

Leave a Reply

Your email address will not be published. Required fields are marked *