0

I searched for all regex exp but didn't find any matching my needs.

In none of the above did I get a solution:

I need to check that the name is valid if
=> First letter every word should be caps
=> Rest all letters of each word should be small
=> Name should have only alpha char A-Z and a-z
=> First word Length should be min 3
=> Name should not have more than one space between words

Ex :
sujay => false
Sujay => true

Sujay u => false
Sujay U => true

Sujay U n => false
Sujay U N => true

SuJay U => false
Sujay UN => false
Sujay Uls => true

Sujay9 => false
Su => false
Su U => false
Sujay U N => true
Sujay Uls Nat=> true

|*| Check function used :

static boolean chkNamVldFnc(String namVar)
{
    String namRegExpVar = "[A-Z][A-Za-z ]{2,}";

    Pattern pVar = Pattern.compile(namRegExpVar);
    Matcher mVar = pVar.matcher(namVar);
    return mVar.matches();
}

|*| Try 1 :

String namRegExpVar = "[A-Z][A-Za-z ]{2,}";

|*| Try 2 :

String namRegExpVar = "[A-Z][a-z]{2,}+//s[A-Z][a-z]{2,}";

|*| Try 3 :

String NamRegExpVar = "[A-Z][a-z]{2,}||[A-Z][a-z]{2,}+//s[A-Z][a-z]";

Kindly help me with Proper Regular Exp :

I also want to know why we should start Reg Exp with ^ and end with $

Laurel
  • 5,965
  • 14
  • 31
  • 57
Sujay U N
  • 4,974
  • 11
  • 52
  • 88

1 Answers1

2

Try:

^[A-Z][a-z]{2,}(?: [A-Z][a-z]*)*$
  • First name must start with letter A-Z, followed by at least 2 letters a-z
  • Optionally, there can be names following the first name, seperated by a space and beginning with letter A-Z, and followed by optional letters a-z
yas
  • 3,520
  • 4
  • 25
  • 38