繁体   English   中英

我正在尝试使用JavaScript控制器中的正则表达式验证字符串?

[英]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 and3 )因此它满足正则表达式。 当存在其他匹配项时,将忽略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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM