0

I'm fairly new to Regex, but not new to Java as a coding language. I'm currently trying to create a Regex expression that will format a user's input to two separate values, but I'm a little curious as to how to approach it.

For example, suppose a user were guessing the resulting score of a basketball game, there's a handful of formats they could use:

     57-89
     57:89
     57/89

etc.

I guess my question is first, how would I go about having my Regex expression handle multiple digits? That is, recognizing a valid guess regardless of how many digits they were to put in for each value. Second of all, how would I go about creating a Regex expression that would handle multiple formats, such as the ones listed above?

Thanks ahead of time.

3
  • If you don't constrain the outputs to begin with you'll have a hard time; what about "fifty seven to eighty nine"? Commented Apr 6, 2014 at 2:58
  • Well, I'm going off of the assumption that the input given will at least be in an integer format. I suppose I could limit it to where my program would only accept input that matches a specific type, but wouldn't that eliminate the purpose of Regex? Commented Apr 6, 2014 at 3:03
  • No, quite the opposite; if you want to work efficiently with regexes you have to know your input text well. Accepting anything and trying to extract valuable data out of it is not what regexes are for. You need to have at least some constraints, and that these constraints are easily expressible with regexes. Commented Apr 6, 2014 at 3:18

1 Answer 1

1

If the input is in the following format:

<integer><non-integer delimiter><integer>

then this split method will parse it into a String[] with each integer as a separate element:

inputString.split("[^0-9]+");

[^0-9]+ is the regex for the delimiter:

  • [] character class;
  • ^ exclude the following characters;
  • 0-9 character range 0, 1, ..., 9;
  • + one or more occurrences (that means it will work for multicharacter delimiter, e.g. 59 - 87).

More information on Java regexes is here.

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

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.