Haha
Haha

Reputation: 1019

Valid regex for number(a,b) format

How can I express number(a,b) in regex? Example:

number(5,2) can be 123.45 but also 2.44

The best I got is: ([0-9]{1,5}.[0-9]{1,2}) but it isn't enough because it wrongly accepts 12345.22.

I thought about doing multiple OR (|) but that can be too long in case of a long format such as number(15,5)

Upvotes: 1

Views: 64

Answers (2)

The fourth bird
The fourth bird

Reputation: 163467

You might use

(?<!\S)(?!(?:[0-9.]*[0-9]){6})[0-9]{1,5}(?:\.[0-9]{1,2})?(?!\S)

Explanation

  • (?<!\S) Negative lookbehind, assert what is on the left is not a non whitespace char
  • (?! Negative lookahead, assert what is on the right is not
    • (?:[0-9.]*[0-9]){6} Match 6 digits
  • ) Close lookahead
  • [0-9]{1,5} Match 1 - 5 times a digit 0-9
  • (?:\.[0-9]{1,2})? Optionally match a dot and 1 - 2 digits
  • (?!\S) Negative lookahead, assert what is on the right is not a non whitespace char

Regex demo

Upvotes: 3

Sunny Patel
Sunny Patel

Reputation: 8077

I don't know Scala, but you would need to input those numbers when building your regular expression.

val a = 5
val b = 2
val regex = (raw"\((?=\d{1," + a + raw"}(?:\.0+)?|(?:(?=.{1," + (a + 1) + "}0*)(?:\d+\.\d{1," + n + "})))‌.+\)").r

This checks for either total digits is 5, or 6 (including decimal) where digits after the decimal are a max of 2 digits. For the above scenario. Of course, this accounts for variable numbers for a and b when set in code.

Upvotes: 0

Related Questions