Issue
I need to validate a String in java to meet below requirement,
- The letters a to z (upper and lowercase) (zero or many times) -
[a-zA-Z]
- The single quote character (zero or one time) -
??
- The space character (zero or one time) -
??
- Any other character should not be accepted
I tried with many expressions but couldn't get to work with the number of occurrences (2nd and 3rd point)
How can I achieve this?
Solution
quote | space ||
-------+-------++-----
0 | 0 || ^[a-z]*$
0 | 1 || ^[a-z]* [a-z]*$
1 | 0 || ^[a-z]*'[a-z]*$
1 | 1 || ^[a-z]* [a-z]*'[a-z]*$ or ^[a-z]*'[a-z]* [a-z]*$
Eg.
final Pattern regex = Pattern
.compile("^([a-z]*|[a-z]* [a-z]*|[a-z]*'[a-z]*|[a-z]* [a-z]*'[a-z]*|[a-z]*'[a-z]* [a-z]*)$",
CASE_INSENSITIVE);
for(String x: asList("", "'", " ", "' '", " a ", "p%q", "aB cd'Ef", "'dF gh"))
System.out.printf("%s <= \"%s\"%n", regex.matcher(x).matches(), x);
With output:
true <= ""
true <= "'"
true <= " "
false <= "' '"
false <= " a "
false <= "p%q"
true <= "aB cd'Ef"
true <= "'dF gh"
Answered By - josejuan
Answer Checked By - Gilberto Lyons (JavaFixing Admin)