The following Java code helps us to allow Empty Space in input keyword/string alongwith the alphabets [a-zA-Z] and numbers [0-9]
The regular expression should be like ^[a-zA-Z0-9 ]+
In this regular expression there is an empty space added before closing bracket ]
and a plus sign is added after the same closing bracket ]
. The output is returned as true
or false
Option-1: Validate the string with the help of Pattern
and Matcher
classes. Both Pattern
and Matcher
classes are added since Java 1.4
version.
package com.learning.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexValidationWithPatternMatcher {
public static void main(String[] args) {
String inputString = "Operating System";
Boolean isValidKeyword = validKeyword(inputString);
System.out.println("Is valid keyword : " + isValidKeyword);
}
public static Boolean validKeyword(String keyword) {
String regex = "^[a-zA-Z0-9 ]+";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(keyword);
return match.matches();
}
}
The code produces the following output:
Is valid keyword : true
Option-2: Validate the string with String
class inbuit matches
method which internally calls Pattern.matches()
method for given regular expression against the value of String
variable. The matcher
method is available in String
class since Java 1.4
version
package com.learning.regex;
public class RegexValidation {
public static void main(String[] args) {
String inputString = "Operating System";
Boolean isValidKeyword = inputString.matches("^[a-zA-Z0-9 ]+");
System.out.println("Is valid keyword : " + isValidKeyword);
}
}
The code produces the following output:
Is valid keyword : true