-6

I need to validate a String in java to meet below requirement,

  1. The letters a to z (upper and lowercase) (zero or many times) - [a-zA-Z]
  2. The single quote character (zero or one time) - ??
  3. The space character (zero or one time) - ??
  4. 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?

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

2
 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"
josejuan
  • 9,338
  • 24
  • 31
-1

To mention, another idea can be to use a negative lookahead.

^(?!.*?([ ']).*\1)[a-zA-Z ']+$

See this demo at regex101

Inside the lookahead ([ ']) captures any of the characters, that are allowed only once. \1 checks for re-occurrence by backreference to what was captured in group 1 with .* anything in between.

This pattern allows to easily add more characters that must not occure more than once.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
  • How can I modify this to accept `numbers 0 to 9 (between zero and three times)` ? – Chamithra Thenuwara Oct 10 '19 at 15:42
  • 1
    @ChamithraThenuwara You could add digits to the character class and add another negative lookahead at start to disallow 4 or more digits: [`^(?!(?:\D*\d){4})(?!.*([ ']).*\1)[a-zA-Z\d ']+$`](https://regex101.com/r/FKuF2l/2) – bobble bubble Oct 10 '19 at 15:49
  • 1
    You're welcome! Those lookhead things are advanced stuff but once understood it's easy and useful :) BTW you can also pipe both negative conditions into one negative lookahead: [`^(?!(?:\D*\d){4}|.*([ ']).*\1)[a-zA-Z\d ']+$`](https://regex101.com/r/FKuF2l/3) – bobble bubble Oct 10 '19 at 15:53