Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex OR |

I'm currently searching how to write correctly a regex for this application :

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

I tried to use a or operator "|", but it doesn't work ;( => /^(\d{1,5})?\.?(\d{1,4})?$|^(\d{1,5})$/ I do not understand why, it's my first java script regex and i'm not sure to use well the "|" operator.

Following the answers I would like to obtain with 1 regex :

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

Thank you very much for your help. Have a nice day.

Etienne

like image 713
Etienne Avatar asked Feb 05 '23 15:02

Etienne


2 Answers

Both rules rolled in to one:

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

Here is a working example

like image 143
musefan Avatar answered Feb 07 '23 12:02

musefan


You could check the second part as optional.

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));
like image 23
Nina Scholz Avatar answered Feb 07 '23 12:02

Nina Scholz