正则表达式替换匹配项,但也会忽略引号内的匹配项

标签 r regex regex-lookarounds stringr

尝试将“and”或“or”匹配并替换为“&”和“|”当它出现在引号之外时,除非它们出现在引号内。

引号可以是单引号 (') 或双引号 (")。

字符串如下:

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 包来进行所有正则表达式操作。

如果您需要更多信息,请告诉我。

最佳答案

您应该考虑一种方法来匹配双引号和单引号子字符串以省略它们并仅处理 andor在所有其他情况下。最简单的方法是使用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 组:要么 andor作为一个完整的词。

请参阅regex demo .

取决于文字 " 的方式和'被逃进里面"..."'...'您需要调整(?:\"[^\"]*\"|'[^']*')正则表达式的一部分。

~ ifelse(z=="or","|", "&")部分是一个回调函数,它接收唯一的参数(在该函数内名为 z ),其内容是您从正则表达式获得的匹配值(即 orand )。如果匹配值等于 or ,匹配项替换为 | ,否则,与 & .

关于正则表达式替换匹配项,但也会忽略引号内的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47530467/

相关文章:

javascript - 按元素和类拆分 html

正则表达式匹配文件名中的字符串,同时排除另一个字符串

r - R Markdown ioslides 的自定义 CSS 应该存储在哪里?

r - R 在复制对象时是否总是复制数据?

Javascript 正则表达式语法错误?

javascript - 用于检查集合的第一个字符和最后一个字符是否不同的正则表达式

正则表达式不匹配字符串中超过一个的尾部斜杠

r - 如何通过从 ggplot 中的不同数据帧映射 aes_string 在 ggplot 中生成图例?

r - 根据条件求和选择行 tidyverse

regex - 使用正则表达式从imap消息中查找大网址