How can I express such a requirement using Java regular expression?

I need to check that the file contains some amounts that correspond to a specific format:

  • between 1 and 15 characters (digits or ",")
  • can contain at most one decimal separator ","
  • must have at least one number before the separator
  • this amount should be in the middle of the line, limited to alphabetic characters (but we must exclude distorted files).

I currently have this:

\d{1,15}(,\d{1,14})?

But this does not meet the requirement, as I can catch up to 30 characters here.
Unfortunately, for some reasons that have been explained here for too long, I can't just select a substring or use any other java call. The match must be in one Java compatible regular expression.

+3
source share
1 answer
^(?=.{1,15}$)\d+(,\d+)?$
  • ^ beginning of line
  • (?=.{1,15}$) a positive forecast to provide a full line length between 1 and 15
  • \d+ one or more digits.
  • (,\d+)?followed by a comma and other numbers
  • $ end of line (not really required as we already checked it in lookahead).

You may need to hide the backslash for Java: ^(?=.{1,15}$)\\d+(,\\d+)?$

update: , \b (^ $).

\b(?=[\d,]{1,15}\b)\d+(,\d+)?\b

java:

"\\b(?=[\\d,]{1,15}\\b)\\d+(,\\d+)?\\b"

:

"\\b(?=[0-9,]{1,15}\\b)[0-9]+(,[0-9]+)?\\b"
+11

Source: https://habr.com/ru/post/1763050/


All Articles