Dart regular expression to check people’s names

Last updated on November 11, 2020 A Goodman Loading... One comment

Examples of human names:

Donand J. Trump
Geogre W. Bush
Walter White 
Brady Hartsfield 
Ken Pat O'Biden
A-Crazy-Name Saitama
Vegeta 

This is a simple regex pattern to check a person’s name in Dart:

r"^\s*([A-Za-z]{1,}([\.,] |[-']| ))+[A-Za-z]+\.?\s*$"

Test it:

void main(){
  RegExp rex = new RegExp(r"^\s*([A-Za-z]{1,}([\.,] |[-']| ))+[A-Za-z]+\.?\s*$");
  
  //// Testing
  
  // Expected ouput: True
  if(rex.hasMatch("Donand J. Trump")){
    print('True');
  } else {
    print("False");
  }
  
  // Expected ouput: True
  if(rex.hasMatch("Brady Hartsfield")){
    print("True");
  } else {
    print("False");
  }
  
  // Expected ouput: True
  if(rex.hasMatch("Ken Pat O'Biden")){
    print("True");
  } else {
    print("False");
  }
  
  // Expected ouput: True
  if(rex.hasMatch("A-Crazy-Name Saitama")){
    print('True');
  } else {
    print("False");
  }
  
  // Expected ouput: False
  if(rex.hasMatch("A wrong name ____ @! ?")){
    print('True');
  } else {
    print("False");
  }
}

Result:

True
True
True
True
False
Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
mavinis
mavinis
8 months ago

This rule only accepts full names.
How can I make it match with a single name without surname?

Related Articles