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 = "302568074@abc.com.cn";
		
		String email2 = "ABC_java@123.com";
		
		String email3 = "abc123def.com.cn";
		
		//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:

302568074@abc.com.cn : true
ABC_java@123.com : true
abc123def.com.cn : false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments