[英]Javascript pattern not matching
I am trying to match pattern which contains pipe(|) operator. 我正在尝试匹配包含pipe(|)运算符的模式。
Have used below code to match patteren 使用下面的代码来匹配模式
var format = /[ \\|]/; // This is the pattern for matching pipe pattern
if ("Near raghavendra temple ring roads".match(format)) {
alert("Invalid character");
}
"Near raghavendra temple ring roads"
this string does not contains | 此字符串不包含"Near raghavendra temple ring roads"
operator but still above condition getting true. 运算符,但仍然超出条件。
Not able to to understand what is the mistake in above pattern. 无法理解上述模式中的错误。
var format = /[\\\\|]/; // This is the pattern for matching pipe pattern if ("Near raghavendra temple ring roads".match(format)) console.log("Invalid character"); else console.log('All valid');
You are matching on the space character. 您正在匹配空格字符。 Remove the space from the regex pattern (inside the square) brackets 从正则表达式模式(方括号内)中删除空格
The problem is you have a space in there: 问题是您那里有空间:
/[ \\|]/
actually means "match any one space, \\
or |
". 实际上表示“匹配任何一个空格, \\
或|
”。
If all you want to do is match a pipe, then use this: 如果您只想匹配管道,请使用以下命令:
const format = /[\\|]/; // This is the pattern for matching pipe pattern if ("Near raghavendra temple ring roads".match(format)) { console.log("Invalid character"); } else { console.log("Okay"); }
You probably have the double- \\
because that's how it needs to appear in strings. 您可能有double- \\
因为这是它需要出现在字符串中的方式。 However, in regex, if you do two, it makes it a \\
literal. 但是,在正则表达式中,如果执行两次,它将使其成为\\
文字。 If you just want to escape the pipe, just use one. 如果您只想逃脱管道,请使用其中一个。
In fact, in a set like that, you don't even need to escape it: 实际上,在这样的集合中,您甚至不需要逃脱它:
const format = /[|]/; // This is the pattern for matching pipe pattern if ("Near raghavendra temple ring roads".match(format)) { console.log("Invalid character"); } else { console.log("Okay"); } if ("Bad | character".match(format)) { console.log('Bad character'); }
Personally, I like to keep the slash though just for clarity. 就个人而言,我只是想保持清晰而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.