尝试将“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 包来进行所有正则表达式操作。
如果您需要更多信息,请告诉我。
最佳答案
您应该考虑一种方法来匹配双引号和单引号子字符串以省略它们并仅处理 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
作为一个完整的词。
请参阅regex demo .
取决于文字 "
的方式和'
被逃进里面"..."
和'...'
您需要调整(?:\"[^\"]*\"|'[^']*')
正则表达式的一部分。
~ ifelse(z=="or","|", "&")
部分是一个回调函数,它接收唯一的参数(在该函数内名为 z
),其内容是您从正则表达式获得的匹配值(即 or
或 and
)。如果匹配值等于 or
,匹配项替换为 |
,否则,与 &
.
关于正则表达式替换匹配项,但也会忽略引号内的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47530467/