我想使用 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
提交
取消