Java Regex Pattern Example

(Last Updated On: August 11, 2016)

Regex [Regular Expression]:

Regular expression is a useful one to match and extract only the required parts.
Eg:
Defining the phone number formats.
Removing unreadable or unwanted characters from a string

Sample Program:

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

public class Regex {
 
	public static void main(String[] args) {
		String inputStr = "?Javadomain.in's a technical,java-blog";
		Pattern pattern = Pattern.compile("[\\s\\?\\,\\-\\']+");
		Matcher matcher = pattern.matcher(inputStr);
		boolean temp = matcher.find();
		System.out.println(temp);
		if (temp) {
			String aftRegex = inputStr.replaceAll("[\\s\\?\\,\\-\\']+", "_");
			System.out.println(aftRegex);
		} else {
			System.out.println("else");
		}

	}

}

Output:

true
_Javadomain.in_s_a_technical_java_blog

Recommended Java Books:

230 total views, 1 views today

Leave a Reply

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