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

ricefieldboy
  • 347
  • 1
  • 4
  • 15

1 Answers1

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, (?:...).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563