Check non-numeric characters in string

后端 未结 2 1160
有刺的猬
有刺的猬 2020-12-17 01:52

I want to check whether the String contains only numeric characters or it contains alpha-numeric characters too.

I have to implement this check in database transacti

2条回答
  •  执笔经年
    2020-12-17 02:12

    You can check this with a regex.

    Suppose that (numeric values only):

    String a = "493284835";
    a.matches("^[0-9]+$"); // returns true
    

    Suppose that (alphanumeric values only):

    String a = "dfdf4932fef84835fea";
    a.matches("^([A-Za-z]|[0-9])+$"); // returns true
    

    As Pangea said in the comments area :

    If the performance are critical, it's preferrable to compile the regex. See below for an example :

    String a = "dfdf4932fef84835fea";
    Pattern pattern = Pattern.compile("^([A-Za-z]|[0-9])+$");
    Matcher matcher = pattern.matcher(a);
    
    if (matcher.find()) {
        // it's ok
    }
    

提交回复
热议问题