Javascript正则表达式OR |

时间:2017-04-19 08:55:03

标签: javascript regex numbers operators

我目前正在搜索如何正确编写此应用程序的正则表达式:

1 - 没有"的数字。"长度为1到5位数 => /^(\d{1,5})$/
2 - 带有"的数字。"在"之前长度为1到5位数。" "和#34;之后的1到4位数字。或以"开头的数字。" "和#34;之后的长度为1到4位数。 => /^(\d{1,5})?\.?(\d{1,4})?$/

我尝试使用或运算符" |",但它不起作用;( => /^(\d{1,5})?\.?(\d{1,4})?$|^(\d{1,5})$/ 我不明白为什么,它是我的第一个java脚本正则表达式,我不确定使用" |"操作

我希望通过 1 正则表达式

获得答案
123 => ok
12345 => ok
123456 => not ok
12345.2156 => ok
123456.12 => not ok
12345.12345 => not ok

非常感谢你的帮助。 祝你有愉快的一天。

艾蒂安

5 个答案:

答案 0 :(得分:4)

这两条规则都卷入了一个:

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

Here is a working example

答案 1 :(得分:3)

您可以将第二部分检查为可选。

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));

答案 2 :(得分:1)

带有双|的{p> ^(\d{1,5}|\d{1,5}\.\d{1,4}|\.\d{1,4})$在这里工作得很好https://regex101.com/r/jTVW2Z/1

答案 3 :(得分:0)

要使用or运算符,如果要捕获匹配的值,则应将正则表达式括在括号/(...)/中,并使用管道/(...|...)/拆分reg。

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

checkNum('55555.4444')
checkNum('88888')
checkNum('88888.22')

答案 4 :(得分: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))

相关问题