匹配正则表达式的正则表达式

我想使用 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 only

const expresion = /[^\|](.*?)(\|)(.*?)*[^$/|]/g

// But this test only gives false for the first pipe at the end not the second

console.log(expresion.test(string))


ibeautiful
浏览 145回答 1
1回答

交互式爱情

该模式[^\|](.*?)(\|)(.*?)*[^$/|]至少匹配一个字符|,但.可以匹配任何字符,也可以匹配另一个字符|请注意,这部分[^$/|]表示除$ / |您可以开始匹配除 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}`));如果不存在换行符,您可以使用:^[^|]+(?:\|[^|]+)+$
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript