2017-03-03 13 views
1

是否有可能使用一個正則表達式獲取所有帶引號的文本?從regexr正則表達式得到所有不是單引號的引用文字

示例文本:

編輯 「表達」 &文本看比賽。翻轉「匹配」或表達細節。 用ctrl-z撤銷錯誤。 保存'收藏夾&「與朋友或社區分享」表達「。使用工具「探索」您的結果。圖書館提供完整的參考&幫助,或觀看視頻教程。

在這種情況下,我想捕捉ExpressionmatchesExplore但不Share因爲'Favorites & "Share" expressions'是單引號。

+0

'「探索」'從結果錯過了什麼? – RomanPerekhrest

+0

哎呀,是的,探險家也應該趕上 – Xeul

+0

你可能只喜歡這個'「。*?」' –

回答

2

不能建立只有你在Javascript中想要的部分相匹配的正則表達式,但是你可以建立所有的字符串相匹配的無間隙的模式,並使用捕獲組抽取您想要的部分:

/[^"']*(?:'[^']*'[^"']*)*"([^"]*)"/g 
#^----------------------^ all that isn't content between double quotes 

由於您的字符串可能喜歡的東西abcd 'efgh "ijkl" mnop' qrst(總之沒有你想要的部分,但與單引號字符串內使用雙引號部分)結束,這是更安全的方式更改爲:

/[^"']*(?:'[^']*(?:'[^"']*|$))*(?:"([^"]*)"|$)/g 

並放棄最後一場比賽。

+0

我從執行這一個得到以下結果: [「編輯」表達式「」表達式「] – Xeul

+0

@Xeul:你需要提取捕獲組1,要做到這一點,你必須使用'RegExp.prototype.exec'而不是'String.prototype.match'。你可以在這裏看到如何使用它:https://developer.mozilla。org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec –

+0

是我正在做/ [^''] *(?:'[^'] *'[^「'] *)* 「([^」] *)「/ g.exec(內容) – Xeul

0

如果沒有特殊的正則表達式:

var mystr = "Edit the \"Expression\" & Text to see matches. Roll over \"matches\" or the expression for details. Undo mistakes with ctrl-z. Save 'Favorites & \"Share\" expressions' with friends or the Community. \"Explore\" your results with Tools. A full Reference & Help is available in the Library, or watch the video Tutorial." 
var myarr = mystr.split(/\"/g) 
var opening=false; 
for(var i=1; i<myarr.length;i=i+2){ 
    if((myarr[i-1].length-myarr[i-1].replace(/'/g,"").length)%2===1){opening=!opening;} 
    if(!opening){console.log(myarr[1]);} 
} 

工作原理:

  • 拆分文本由"

  • 奇數的索引是字符串"包裝

  • ,如果在此之前IND前,中'存在奇數,此項目由'包裹,不應該被視爲

相關問題