2

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.

7
  • what is wrong with this way? Commented Sep 30, 2016 at 19:47
  • 1
    The pattern: ^\D*\d\D*$. Commented Sep 30, 2016 at 19:48
  • It seems that I am not getting the correct result with this way. Let me double check Commented Sep 30, 2016 at 19:49
  • if a string contains anywhere? I'd be tempted to just write if(str.length == 1 && isDigit(str[0]). isDigit from std.ascii is good enough for a basic check. Commented Sep 30, 2016 at 19:50
  • 3
    Note that the "d" tag is used for the D programming language, please refrain from using it just because you happen to have a "d" in your example Commented Sep 30, 2016 at 19:56

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Jan In the same regex how can we check if digits are between 0-6 only
1

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;

Comments

-1

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.

2 Comments

he asked for checking if the string contains a digit and is not only a digit. But it should only contain exactly one digit
@WebFreak001 yes, you are correct. The string itself contains parentheses also, but I am checking if it contains only one digit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.