2

What i want is to check if there is a number followed by spaces and another number, without any "," in between, anywhere in the String

Currently i am doing this:

Pattern pattern = Pattern.compile("[0-9][\" \"]+[0-9]");
Matcher matcher = pattern.matcher(input);
if(matcher.find()) return false;

and it works just fine. But i was wondering if there is any other simpler way of achieving this?

2 Answers 2

1

Since it's an assignment, I won't write out the code, but an alternative solution is:

  • Split the string on the , token (using String.split())
  • For each member of the resulting split array:
    • Trim the leading and trailing spaces from the member
    • If the trimmed member is an integer (I'll let you figure out how to determine that):
      • It doesn't meet the criteria you specified
    • Else:
      • It's possible that the token could meet your criteria (of containing multiple integers and spaces but no commas. There are several ways you could determine this: do a split on " "; use a while loop, or maybe something else. I'll let you figure that out.
Sign up to request clarification or add additional context in comments.

2 Comments

No, in that case, split[0] would be 1 2 (the space would be preserved), which of course isn't an integer.
Ah, I think I was trying to just check if each token is an integer, but you're looking for the case where two or more integers are not properly separated. I updated my answer, that should be more than enough to get you started.
0

Your solution is good enough, you could try by the positive way like

Pattern pattern = Pattern.compile("^[1-9](,[1-9])*$");
Matcher matcher = pattern.matcher(input);
if(matcher.matches()) return true;

Comments

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.