ibeautiful
2023-08-24 15:41:54
我想使用 JavaScript 和 Regex 檢查測試是否僅驗證管道之間的任何類型的字符串|所以這些將測試真實`word|a phrase|word with number 1|word with symbol?``word|another word`但其中任何一個都會說假`|word``word|``word|another|``word`我試過這個const string = 'word|another word|'// Trying to exclude pipe from beginning and end onlyconst expresion = /[^\|](.*?)(\|)(.*?)*[^$/|]/g// But this test only gives false for the first pipe at the end not the secondconsole.log(expresion.test(string))
1 回答

交互式愛情
TA貢獻1712條經驗 獲得超3個贊
該模式[^\|](.*?)(\|)(.*?)*[^$/|]
至少匹配一個字符|
,但.
可以匹配任何字符,也可以匹配另一個字符|
請注意,這部分[^$/|]
表示除$
/
|
您可以開始匹配除 a|
或換行符之外的任何字符。
然后重復至少 1 次或多次匹配 a,|
后跟除 a 之外的任何字符|
^[^|\r\n]+(?:\|[^|\r\n]+)+$
解釋
^
字符串的開頭[^|\r\n]+
否定字符類,匹配|
除換行符之外的任何字符 1+ 次(?:
非捕獲組\|[^|\r\n]+
匹配|
后跟除 a|
或換行符之外的任何字符 1+ 次)+
關閉組并重復 1 次以上以匹配至少一個管道$
字符串結尾
const pattern = /^[^|\r\n]+(?:\|[^|\r\n]+)+$/;
[
"word|a phrase|word with number 1|word with symbol?",
"word|another word",
"|word",
"word|",
"word|another|",
"word"
].forEach(s => console.log(`${pattern.test(s)} => ${s}`));
如果不存在換行符,您可以使用:
^[^|]+(?:\|[^|]+)+$
添加回答
舉報
0/150
提交
取消