Java Regex to Validate Full Name allow only Spaces and Letters

前端 未结 14 2348
抹茶落季
抹茶落季 2020-11-28 04:50

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.

相关标签:
14条回答
  • 2020-11-28 04:55

    try this regex (allowing Alphabets, Dots, Spaces):

    "^[A-Za-z\s]{1,}[\.]{0,1}[A-Za-z\s]{0,}$" //regular
    "^\pL+[\pL\pZ\pP]{0,}$" //unicode
    

    This will also ensure DOT never comes at the start of the name.

    0 讨论(0)
  • 2020-11-28 04:56

    Regex pattern for matching only alphabets and white spaces:

    String regexUserName = "^[A-Za-z\\s]+$";
    
    0 讨论(0)
  • 2020-11-28 04:59

    Accept only character with space :-

     if (!(Pattern.matches("^[\\p{L} .'-]+$", name.getText()))) {
        JOptionPane.showMessageDialog(null, "Please enter a valid character", "Error", JOptionPane.ERROR_MESSAGE);
        name.setFocusable(true);
        }  
    
    0 讨论(0)
  • 2020-11-28 05:00

    My personal choice is: ^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$, Where:

    ^\p{L}+ - It should start with 1 or more letters.

    [\p{Pd}\p{Zs}'\p{L}]* - It can have letters, space character (including invisible), dash or hyphen characters and ' in any order 0 or more times.

    \p{L}+$ - It should finish with 1 or more letters.

    |^\p{L}+$ - Or it just should contain 1 or more letters (It is done to support single letter names).

    Support for dots (full stops) was dropped, as in British English it can be dropped in Mr or Mrs, for example.

    0 讨论(0)
  • 2020-11-28 05:03

    please try this regex (allow only Alphabets and space)

    "[a-zA-Z][a-zA-Z ]*"

    if you want it for IOS then,

    NSString *yourstring = @"hello";
    
    NSString *Regex = @"[a-zA-Z][a-zA-Z ]*";
    NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    
    if ([TestResult evaluateWithObject:yourstring] == true)
    {
        // validation passed
    }
    else
    {
        // invalid name
    }
    
    0 讨论(0)
  • 2020-11-28 05:06

    To support language like Hindi which can contain /p{Mark} as well in between language characters. My solution is ^[\p{L}\p{M}]+([\p{L}\p{Pd}\p{Zs}'.]*[\p{L}\p{M}])+$|^[\p{L}\p{M}]+$

    You can find all the test cases for this here https://regex101.com/r/3XPOea/1/tests

    0 讨论(0)
提交回复
热议问题