1

I want to write some code that checks whether the input from user matches a specific format. The format is 's' followed by a space and a number, if the input was "s 1 2 3 4", it would call some function. "s 1 2" would also be acceptable. So far I found that this regex works for a specified amount of times:

if (inputLine.matches("s \\d+ \\d+")) { }

works for 2 numbers after the s, but I need to be able to accept any number of numbers after the s. Any idea on a regex that would suit my needs? Thank you

1
  • 2
    Try this. "s( \\d+)+" There is a space after the opening bracket Commented Dec 7, 2016 at 23:07

1 Answer 1

4

Change your regex to

if (inputLine.matches("s(?: \\d+)+")) { }

to match s, space and 1+ sequences of a space followed with 1+ digits.

If you allow 0 numbers after s, replace the last + quantifier with * to match zero or more occurrences.

Since the repeated capturing groups overwrite the group contents, it makes no sense using a capturing group here, thus, I suggest using a non-capturing one, (?:...).

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

1 Comment

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.