Home > OS >  Create a regex that includes decimal numbers and a maximum of length
Create a regex that includes decimal numbers and a maximum of length

Time:10-21

I'm trying to create a regex pattern that accepts decimal numbers and the maximum length should be 3. These are the regex I tried but didn't work

new RegExp('d{1-3}')
new RegExp('^[0-9]{3}$')

I want to achive to allow the decimal numbers between 0-999.

For example 185.5

Thanks in advance.

CodePudding user response:

you can try this: ^[1-9]{0,3}$

it only accept numbers with max length of 3

example: 123

and if you want it with complex numbers use this:

^[1-9]{0,3}([,.][0-9]{0,3})?$

example: 154.234

CodePudding user response:

here is one way to do it, which matches any number b/w 0 and 999 including decimal values (unlimited)

^(\d{,3}(\.)?(?(2)\d*|$))$

#  should start and ends with a digit
# \d{,3} : match at most 3 digit
# (\.)? : optional period
# ?(?(2) : if period exist match the following pattern
# \d* : match any number of digits after period
# $ : else it should be end of pattern


https://regex101.com/r/B8jRG6/1

CodePudding user response:

regExp ^\d ((\.)|(\.\d{1,3})?)$

Explanation
`^` asserts position at start of a line
`\d` matches a digit (equivalent to `[0-9]`)
` ` matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
1st Capturing Group `((.)|(.\d{0,1})?)`
1st Alternative `(.)`
2nd Capturing Group `(.)`
`.` matches any character (except for line terminators)
2nd Alternative `(.\d{0,1})?`
3rd Capturing Group `(.\d{0,1})?`
`?` matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
`.` matches any character (except for line terminators)
`\d` matches a digit (equivalent to [0-9])
`{0,1}` matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
`$` asserts position at the end of a line
  • Related