pmcg521
pmcg521

Reputation: 349

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.

Upvotes: 2

Views: 7491

Answers (3)

Andy Turner
Andy Turner

Reputation: 140318

If you fancied not using a regular expression:

int numDigits = 0;
for (int i = 0; i < current_Operation.length() && numDigits < 2; ++i) {
  if (Character.isDigit(currentOperation.charAt(i))) {
    ++numDigits;
  }
}
return numDigits == 1;

Upvotes: 1

Jan
Jan

Reputation: 43169

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).

Upvotes: 8

Chloe
Chloe

Reputation: 26264

Use the regular expression

/^\d$/

This will ensure the entire string contains a single digit. The ^ matches the beginning of the line, and the $ matches the end of the line.

Upvotes: -1

Related Questions