[英]I am trying to validate a date with a regular expression in JavaScript but it is not working correctly?
[英]I am trying to validate a string with a regular expression in the javascript controller?
我正在尝试使用正则表达式验证字符串。 该字符串应仅包含列出的单词和字符。
(即)字符串可以接受和(或)数字,(,)和空格。
我尝试使用正则表达式,但是它没有按预期工作。
/(\d|and|or|not|\(|\)|\s)*/
当我在salesforce lightning组件controller.js
它时,它不提供扩展结果。
input : 1 and ( 2 or 3 )
expected output : true
input : 1 aaa ( 2 or 3 )
expected output : false
提前致谢。
问题是,你已经确定你需要的任何数量的这些,你不关心的位置。 因此字符串1 aaa ( 2 or 3 )
匹配1
,以及 (空格),
(
, 2
and
, 3
)
因此它满足正则表达式。 当存在其他匹配项时,将忽略aaa
不匹配的事实。
但是,如果使用起始锚和结束锚 ^
和$
,则定义您的整个输入必须符合此模式,而不是其任何子部分,这正是您想要的:
const regex = /^(\\d|and|or|not|\\(|\\)|\\s)*$/; console.log(regex.test("1 and ( 2 or 3 )")); // true console.log(regex.test("1 aaa ( 2 or 3 )")); // false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.