1

Condition:

  • numbers can be either int or double (total 8 digits)
  • numbers can only be separated by spaces (one or many) and commas (0 or one)
  • commas can only be inside numbers (there can be no commas at the beginning and end of a line)
  • there may be spaces at the beginning of the line (one or many)
  • there may be spaces at the end of the line (one or many)

What I do:

([\s]*\d+(\.{1}\d+)?[\s\,\s]+){7}(\d+(\.{1}\d+)?[\s]*){1}
                    ^ this   ^

That's ok, except for one condition.
On this string I get true, but need false:

String s1 = " 0 , 4.4 3.2,, 4.1      2 4 1 7.7";

I can't do this:

Numbers can be separated by only one comma or no comma, but in this case there must be a space (one or many).

9
  • you can use (?:,?|\s+) for (zero or one comma) or (1 or more spaces) Commented Aug 29, 2020 at 23:06
  • 1. Does "total 8 numbers" mean "total 8 digits"? 2. Try replacing [\s,\s]+ with (?:\s*,?\s*|\s+) (assuming a comma can have spaces around it) Commented Aug 29, 2020 at 23:08
  • @n199a good catch Commented Aug 29, 2020 at 23:09
  • @Gryphon, write as answer :) Commented Aug 29, 2020 at 23:12
  • @cid Shouldn't it be (?:,|\s+)? Otherwise, the regex would match the empty string. Commented Aug 29, 2020 at 23:16

1 Answer 1

1

This is the one I came up with for the spaces/commas (also removed some redundant parts):

Pattern.compile("([\\s]*\\d+(\\.\\d+)?(?:\\s*,\\s*|\\s+)){7}(\\d+(\\.\\d+)?[\\s]*)");

Seems to do what you want with the sample you provided, at least. (The use of {1} is generally implied for the places you used it, so I removed those)

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.