Regular Expression Javascript OR |

I am currently looking for the correct way to write a regular expression for this application:

1 - Number without "." with a length of 1 to 5 digits => /^(\d{1,5})$/
2 - Number with "." with a length of 1 to 5 digits to "." . and 1 to 4 digits after "." or a number starting with "." with a length of 1 to 4 digits after the "." . =>/^(\d{1,5})?\.?(\d{1,4})?$/

I tried using either the "|" operator, but it does not work; (=> /^(\d{1,5})?\.?(\d{1,4})?$|^(\d{1,5})$/ I don’t understand why, this is my first java script regex, and I'm not sure that I use the "|" operator well.

After the answers I would like to get with 1 regex:

123 => ok
12345 => ok
123456 => not ok
12345.2156 => ok
123456.12 => not ok
12345.12345 => not ok

Many thanks for your help. Have a nice day.

Etienne

+4
5

:

^\d{1,5}$|^\d{0,5}\.\d{1,4}$

+4

.

function check(v) {
    return /^(?=.)\d{0,5}(\.\d{1,4})?$/.test(v);
}

console.log(['', '.123', 123, 12345, 12345.2156, 123456, 123456.12, 12345.12345].map(check));
Hide result
+3

^(\d{1,5}|\d{1,5}\.\d{1,4}|\.\d{1,4})$ | https://regex101.com/r/jTVW2Z/1

+1

, , , /(...)/ /(...|...)/.

const checkNum = s => console.log(s, /^(\d{1,5}|\d{1,5}\.\d{4})*$/.test(s))

checkNum('55555.4444')
checkNum('88888')
checkNum('88888.22')
Hide result
0

Array#split. , .

function check(a){
 var c= a.toString().split(".");
   return c[1]? ((c[0].length <= 5) && (c[1].length <= 4)) ? true : false : c[0].length <= 5 ? true : false;
}
console.log(check(123))
console.log(check(12345))
console.log(check(123456))
console.log(check(12345.2156))
console.log(check(123456.12))
console.log(check(12345.12345))
Hide result
0

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


All Articles