簡體   English   中英

正則表達式替換匹配但在引號內匹配時也會忽略

[英]Regex to replace matches but also ignore when matches within quotes

嘗試匹配並將“和”或“或”替換為“&”和“|” 當它出現在引號之外,除非它們出現在引號內。

引號可以是單引號(')或雙引號(“)。

字符串如下:

Industry ='Education' or Industry =\"Energy\" or Industry = 'Financial or Bank' or Industry = 'Hospitality' or Industry = \"Food and Beverage\"  and Industry = 'Utilities'

預期產量:

Industry ='Education' | Industry =\"Energy\" | Industry = 'Financial or Bank' | Industry = 'Hospitality' | Industry = \"Food and Beverage\"  & Industry = 'Utilities'

我知道我們可能不得不使用外觀,但無法弄清楚如何。 我在R中使用stringr包進行所有正則表達式操作。

如果您需要更多信息,請告訴我。

您應該考慮一種方法來匹配雙引號和單引號子串以省略它們,並且只處理and / or在所有其他上下文中。 最簡單的方法是使用gsubfn ,你可以傳遞一個PCRE正則表達式,它正是這樣做的:

> library(gsubfn)
> x <- "Industry ='Education' or Industry =\"Energy\" or Industry = 'Financial or Bank' or Industry = 'Hospitality' or Industry = \"Food and Beverage\"  and Industry = 'Utilities'"
> pat = "(?:\"[^\"]*\"|'[^']*')(*SKIP)(*F)|\\b(and|or)\\b"
> gsubfn(pat, ~ ifelse(z=="or","|", "&"), x, backref=0, perl=TRUE)
[1] "Industry ='Education' | Industry =\"Energy\" | Industry = 'Financial or Bank' | Industry = 'Hospitality' | Industry = \"Food and Beverage\"  & Industry = 'Utilities'"

(?:\\"[^\\"]*\\"|'[^']*')(*SKIP)(*F)|\\\\b(and|or)\\\\b模式將匹配:

  • (?: - 一個變更組:
    • \\"[^\\"]*\\" - 雙引號子字符串,里面沒有雙引號
    • | - 要么
    • '[^']*' - 單引號子字符串
  • ) - 小組結束
  • (*SKIP)(*F) - 棄掉比賽,繼續尋找下一場比賽
  • | - 要么
  • \\\\b(and|or)\\\\b - 第1組:一個and / or整個單詞。

請參閱正則表達式演示

根據文字"'如何在"..."'...'內轉義,你需要調整(?:\\"[^\\"]*\\"|'[^']*')正則表達式的一部分。

~ ifelse(z=="or","|", "&")部分是一個回調函數,它接收唯一的參數(在此函數中命名為z ),其內容是從正則表達式獲得的匹配值(即or或者and )。 如果匹配值等於or ,則匹配將替換為| ,否則,用&

這是一種丑陋的方式,但它適用於您的具體情況:

對於Or:

(?:'|")(?:.*?)(?:'|")(?:.*?)(or)(?:.*?)

為和:

(?:'|")(?:.*?)(?:'|")(?:.*?)(and)(?:.*?)

我建議使用https://regex101.com/來幫助構建和測試你的正則表達式

您的問題存在潛在問題,因為嵌套內容可能無法通過單個正則表達式處理得很好或根本無法處理。 話雖如此,如果我們假設您想要通過管道替換的值or值總是出現帶引號的字符串之后,那么我們可以嘗試以下方法:

gsub("([\"'])\\s*or", "\\1 |", input)
[1] "Industry ='Education' | Industry =\"Energy\" | Industry = 'Financial or Bank' |
Industry = 'Hospitality' | Industry = \"Food and Beverage\"  and Industry = 'Utilities'"

通過檢查,在引用的字符串內發生的or值被兩個不帶引號的單詞包圍。 顯然,這可能會在看到其他數據或更多嵌套內容時崩潰。

演示

暫無
暫無

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

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