繁体   English   中英

Javascript模式不匹配

[英]Javascript pattern not matching

我正在尝试匹配包含pipe(|)运算符的模式。

使用下面的代码来匹配模式

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" 运算符,但仍然超出条件。

无法理解上述模式中的错误。

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

您正在匹配空格字符。 从正则表达式模式(方括号内)中删除空格

问题是您那里有空间:

/[ \\|]/

实际上表示“匹配任何一个空格, \\| ”。

如果您只想匹配管道,请使用以下命令:

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

您可能有double- \\因为这是它需要出现在字符串中的方式。 但是,在正则表达式中,如果执行两次,它将使其成为\\文字。 如果您只想逃脱管道,请使用其中一个。

实际上,在这样的集合中,您甚至不需要逃脱它:

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

就个人而言,我只是想保持清晰而已。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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