0

I have the following regular expression:

^(MIN|MAX|SUM|AVERAGE):[(\\d+(\\.\\d+)?), ]+$

The rule I am attempting to implement should allow only for strings of the following format:

OPERATION: (comma separated list of integers or real numbers)

For example the following must be allowed:

MIN: 7, 89.7, 67
AVERAGE: 67.9, 89, 9

However, it accepts input of the form

MAX: , 

How can I avoid having blank spaces on either side of the comma to be accepted?

1
  • what about negative numbers, or scientific notation?
    – leonbloy
    May 9, 2013 at 13:38

5 Answers 5

1

You can use this regex

^(MIN|MAX|SUM|AVERAGE):\s*\d+(\.\d+)?(\s*,\s*\d+(\.\d+)?)*$
1

Character classes can not contain regex constructs, as you have attempted.

This is a slightly different spin on the other answers that results in a smaller regex:

(MIN|MAX|SUM|AVERAGE): \\d+(\\.\\d+)?(, \\d+(\\.\\d+)?)*

The don't need the leading and trailing ^ and $ - they are implied.

To use:

if (str.matches("(MIN|MAX|SUM|AVERAGE): \\d+(\\.\\d+)?(, \\d+(\\.\\d+)?)*") {
    // yes, format is OK
}
4
  • the use of ^,$ depends on the method he's using to match!
    – Anirudha
    May 9, 2013 at 13:54
  • @Anirudh There is only String.match() which must match the entire input, which is why the start/end is redundant
    – Bohemian
    May 9, 2013 at 13:55
  • @Bohemian What about Matcher.find()? May 9, 2013 at 14:03
  • 1
    @PatriciaShanahan what about it? He's not parsing, he's validating input: should allow only for strings of the following format. String.matches() is the only sane choice.
    – Bohemian
    May 9, 2013 at 14:05
0

Try

"^(MIN|MAX|SUM|AVERAGE)\\s?:\\s?(\\d+(\\.\\d+)?)(,\\s?\\d+(\\.\\d+)?)*$"

Tests:

MIN:4: true
MIN:4,4: true
MIN:4, 5: true
MIN:4 , 5: false
MIN: 7, 89.7, 67: true
AVERAGE: 67.9, 89, 9: true
MAX: , : false
0
0

this will accept any of your "operations", the ":" symbol and any numer/dot, comma-separated, with or without spaces before the 1st number or after any comma. It will also prevent your line to end with a comma.

Pattern pattern = Pattern.compile("^(MIN|MAX|SUM|AVERAGE):\\s?(\\d+?(\\.\\d+?)?,?\\s?)+?\\d$");
-1

You have a blank space in you pattern, so you'd have to tweak it a little, the quickest alteration would be this, so that you can still have blank spaces in between your list elements:

"^(MIN|MAX|SUM|AVERAGE):[(\d+(\.\d+)?)][(\d+(\.\d+)?), ]+$"
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.