Search code examples
javaregexstringdigit

Using regex to check if a string contains only one digit


I'm writing an algorithm and I need to check if a string contains only one digit (no more than one). Currently I have:

if(current_Operation.matches("\\d")){
...
}

Is there a better way to go about doing this? Thanks.


Solution

  • You can use:

    ^\\D*\\d\\D*$
    # match beginning of the line
    # non digits - \D*
    # one digit - \d
    # non digits - \D*
    # end of the line $
    

    See a demo on regex101.com (added newlines for clarity).