How to Format a String Using Regular Expression in Java

In this example, you can compile a given regular expression into a pattern, get a Matcher of a given string, and use the matches() method to tell. You can also use the macthes() method in the String object.

Source Code

package com.beginner.examples;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularMatchTest {

	public static void main(String[] args) {
		//String to be judged
		String email1 = "";
		String email2 = "";
		String email3 = "";
		//Rules for matching mailbox Numbers
		String re = "w+@w+(.w{1,3})+";
		System.out.println(email1+" : "+myMatches(email1, re));
		System.out.println(email2+" : "+myMatches(email2, re));
		System.out.println(email3+" : "+myMatches(email3, re));

	//This method is used to match whether a string conforms to a given rule
	public static boolean myMatches(String str,String re) {
		//The rules are sealed as a Pattern object
		Pattern pattern = Pattern.compile(re);
		//Get the Matcher
		Matcher matcher1 = pattern.matcher(str);
		//Returns the result
		return matcher1.matches();


Output: : true : true : false


Imported packages in Java documentation:

Notify of
Inline Feedbacks
View all comments