簡體   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