Regular Expression related: first character alphabet second onwards alphanumeric+some special characters

前端 未结 3 1629
無奈伤痛
無奈伤痛 2021-02-06 03:46

I have one question related with regular expression. In my case, I have to make sure that first letter is alphabet, second onwards it can be any alphanumeric + some special char

相关标签:
3条回答
  • 2021-02-06 03:56

    I think the simplest answer is to pick and match only the first character with regex.

    String str = "s12353467457458";
    if ((""+str.charAt(0)).matches("^[a-zA-Z]")){
        System.out.println("Valid");
    }
    
    0 讨论(0)
  • 2021-02-06 04:17

    Try something like this:

    ^[a-zA-Z][a-zA-Z0-9.,$;]+$
    

    Explanation:

    ^                Start of line/string.
    [a-zA-Z]         Character is in a-z or A-Z.
    [a-zA-Z0-9.,$;]  Alphanumeric or `.` or `,` or `$` or `;`.
    +                One or more of the previous token (change to * for zero or more).
    $                End of line/string.
    

    The special characters I have chosen are just an example. Add your own special characters as appropriate for your needs. Note that a few characters need escaping inside a character class otherwise they have a special meaning in the regular expression.

    I am assuming that by "alphabet" you mean A-Z. Note that in some other countries there are also other characters that are considered letters.

    More information

    • Character Classes
    • Repetition
    • Anchors
    0 讨论(0)
  • 2021-02-06 04:17

    Try this :

     /^[a-zA-Z]{1}/
    

    where

     ^ -> Starts with 
     [a-zA-Z] -> characters to match 
     {1} -> Only the first character
    
    0 讨论(0)
提交回复
热议问题