Java Regex Pattern Example

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:

[java gutter=”false”]
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");
}

}

}
[/java]

Output:
[plain gutter=”false”]
true
_Javadomain.in_s_a_technical_java_blog
[/plain]

Recommended Java Books:

Leave a Reply