簡體   English   中英

正則表達式匹配兩個詞之間的字符串,其中結束邊界詞是可選的

[英]Regex to match string between two words, where the ending boundary word is optional

我想所謂的匹配單詞和寬度之間的文字也依然匹配即使寬度缺失。 例如

在這句話中,我要搭配瑪麗珍

“用忍者創建一個名為Mary Jane的文本字段”

這里我仍然想匹配 Mary Jane,即使之后沒有with子句

創建一個名為Mary Jane的文本字段。

我的正則表達式僅在with存在時匹配,但如果不存在則不匹配。

"Create a picklist called Mary Jane with the value ox'".match(/called(.*)(?:with)/i) // Matches "Mary Jane"

"Create a picklist called Mary Jane'".match(/called(.*)(?:with)/i) // Error: Does not match anything

如何編寫可以匹配兩種情況的正則表達式?

要匹配沒有前導空格和點的名稱,您可以使用帶有交替的捕獲組:

\bcalled (.*?)(?: with|\.?$)
  • \\bcalled匹配字面上的字邊界
  • (.*?)捕獲組 1,匹配除換行符以外的任何字符
  • (?:非捕獲組
    • with字面上的匹配
    • | 或者
    • \\.?$匹配一個可選的點並斷言字符串的結尾
  • )關閉非捕獲組

正則表達式演示

你可以這樣做。 這就是我想出的。 我希望它有幫助。

 let str1 = "Create a text field called Mary Jane with ninja"; let str2 = "Create a text field called Mary Jane"; console.log(words(str1)); console.log(words(str2)); function words(str){ let arr = str.split(" "); let i = arr.indexOf("called"); let j = arr.indexOf("with"); if( j == -1){ return arr.slice(i+1); } return arr.slice(i+1,j); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM