为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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}`));

如果不存在换行符,您可以使用:

^[^|]+(?:\|[^|]+)+$


查看完整回答
反对 回复 2023-08-24
  • 1 回答
  • 0 关注
  • 168 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号