Java Regex Pattern to allow characters and spaces Example

Java Regex Pattern to allow characters and spaces Example:

Requirements:
[plain gutter=”false”]
Java domain – Should be allowed
– Should Not allowed
Java – Should be allowed
(Java) – Should Not allowed
Javadomain – Should be allowed
[/plain]

Java Regex Program to allow characters and whitespaces And also not allow only whitespaces:
[java gutter=”false”]
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexSpace {

public static void main(String[] args) {
String input = " Java domain ";
Pattern regex = Pattern
.compile("^$|[~\\!\\@\\#\\$\\%\\^\\&\\.\\,\\*\\(\\)\\_\\+\\=\\{\\}\\|\\:\\\\’\\[\\]\\<\\>\\?\\/\\’\\^[0-9]]");
Matcher matcher = regex.matcher(input.trim());
if (matcher.find()) {
System.out.println("Not Allowed");
} else {
System.out.println("Allowed");
}
}

}
[/java]

Output:
[plain gutter=”false”]
Allowed
[/plain]

Recommended Java Books:

Leave a Reply