[英]Regex for a matching regex
I want to check with JavaScript & Regex that a test only validates any kind of string between pipes |
我想用 JavaScript 和 Regex 检查测试只验证管道之间的任何类型的字符串
|
So these will test true所以这些将测试为真
`word|a phrase|word with number 1|word with symbol?`
`word|another word`
But any of these will say false但其中任何一个都会说假
`|word`
`word|`
`word|another|`
`word`
I have tried this我试过这个
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))
The pattern [^\\|](.*?)(\\|)(.*?)*[^$/|]
matches at least a single |
模式
[^\\|](.*?)(\\|)(.*?)*[^$/|]
匹配至少一个|
but the .
但是
.
can match any character, and can also match another |
可以匹配任意字符,也可以匹配另一个
|
Note that this part [^$/|]
mean any char except $
/
|
请注意,这部分
[^$/|]
表示除$
/
|
之外的任何字符
You can start the match matching any character except a |
您可以开始匹配除
|
之外的任何字符的匹配|
or a newline.或换行符。
Then repeat at least 1 or more times matching a |
然后重复至少 1 次或多次匹配一个
|
followed by again any character except a |
后跟除
|
之外的任何字符
^[^|\r\n]+(?:\|[^|\r\n]+)+$
Explanation解释
^
Start of string ^
字符串开始[^|\\r\\n]+
Negated character class, match 1+ times any char except |
[^|\\r\\n]+
否定字符类,匹配 1+ 次除|
之外的任何字符or a newline(?:
Non capture group (?:
非捕获组
\\|[^|\\r\\n]+
Match |
\\|[^|\\r\\n]+
匹配|
followed by 1+ times any char except a |
|
之外的任何字符or newline)+
Close group and repeat 1+ times to match at least a single pipe )+
关闭组并重复 1+ 次以匹配至少一个管道$
End of string $
字符串结尾 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}`));
If there will be no newlines present, you can use:如果不存在换行符,您可以使用:
^[^|]+(?:\|[^|]+)+$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.