简体   繁体   English

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

[英]I am trying to validate a string with a regular expression in the javascript controller?

I am trying to validate a string with regex. 我正在尝试使用正则表达式验证字符串。 that the string should contain only the listed words and characters. 该字符串应仅包含列出的单词和字符。

(ie) the string can accept and, or, not, numbers, (,) and blankspace. (即)字符串可以接受和(或)数字,(,)和空格。

I tried with a regular expression but its not working as expected. 我尝试使用正则表达式,但是它没有按预期工作。

/(\d|and|or|not|\(|\)|\s)*/

when i am using this in salesforce lightning component controller.js its is not providing the expexted result. 当我在salesforce lightning组件controller.js它时,它不提供扩展结果。

input : 1 and ( 2 or 3 )
expected output : true

input : 1 aaa ( 2 or 3 )
expected output : false

thanks in advance. 提前致谢。

The problem is that you've define that you need any number of these and you don't care about the position. 问题是,你已经确定你需要的任何数量的这些,你不关心的位置。 So the string 1 aaa ( 2 or 3 ) matches 1 , as well as 因此字符串1 aaa ( 2 or 3 )匹配1 ,以及 (space), ( , 2 , and , 3 , ) therefore it satisfies the regex. (空格), (2 and3 )因此它满足正则表达式。 The fact that there is aaa which doesn't match is ignored when there are other things that do match. 当存在其他匹配项时,将忽略aaa不匹配的事实。

However, if you use the start and end anchors ^ and $ , that defines that your entire input must conform to this pattern as opposed to any sub-portion of it, which is exactly what you want: 但是,如果使用起始锚和结束锚 ^$ ,则定义您的整个输入必须符合此模式,而不是其任何子部分,这正是您想要的:

 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