Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex to Validate Full Name allow only Spaces and Letters

I want regex to validate for only letters and spaces. Basically this is to validate full name. Ex: Mr Steve Collins or Steve Collins I tried this regex. "[a-zA-Z]+\.?" But didnt work. Can someone assist me please p.s. I use Java.

public static boolean validateLetters(String txt) {      String regx = "[a-zA-Z]+\\.?";     Pattern pattern = Pattern.compile(regx,Pattern.CASE_INSENSITIVE);     Matcher matcher = pattern.matcher(txt);     return matcher.find();  } 
like image 775
amal Avatar asked Apr 04 '13 07:04

amal


People also ask

How do you check if a string contains only alphabets and space in Java regex?

We can use the regex ^[a-zA-Z]*$ to check a string for alphabets. This can be done using the matches() method of the String class, which tells whether the string matches the given regex.

What does \b mean in regex Java?

In Java, "\b" is a back-space character (char 0x08 ), which when used in a regex will match a back-space literal.

How do you restrict whitespace in regex?

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.


1 Answers

What about:

  • Peter Müller
  • François Hollande
  • Patrick O'Brian
  • Silvana Koch-Mehrin

Validating names is a difficult issue, because valid names are not only consisting of the letters A-Z.

At least you should use the Unicode property for letters and add more special characters. A first approach could be e.g.:

String regx = "^[\\p{L} .'-]+$"; 

\\p{L} is a Unicode Character Property that matches any kind of letter from any language

like image 67
stema Avatar answered Sep 20 '22 10:09

stema