亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

匹配正則表達式的正則表達式

匹配正則表達式的正則表達式

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 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號