Regex for checking if a string is strictly alphanumeric

前端 未结 10 2048
予麋鹿
予麋鹿 2020-12-01 12:02

How can I check if a string contains only numbers and alphabets ie. is alphanumeric?

10条回答
  •  眼角桃花
    2020-12-01 12:15

    If you want to include foreign language letters as well, you can try:

    String string = "hippopotamus";
    if (string.matches("^[\\p{L}0-9']+$")){
        string is alphanumeric do something here...
    }
    

    Or if you wanted to allow a specific special character, but not any others. For example for # or space, you can try:

    String string = "#somehashtag";
    if(string.matches("^[\\p{L}0-9'#]+$")){
        string is alphanumeric plus #, do something here...
    }
    

提交回复
热议问题