[英]How to index and gsub a string within a dataframe using regex in R
[英]How to specify a repeated pattern within one string using `sub()` instead of `gsub()` in R
我知道有很多答案說明如何匹配單個字符串中的多個匹配項。 但是,我還找不到能夠提供以下原因的上下文的答案:
## A string for which I want to replace `red` and `Red` with `RED`
x <- c("redflag flagred red and Red")
## This one works using `gsub()`
gsub("\\b(?:red|Red)\\b", "RED", x)
#[1] "redflag flagred RED and RED"
但是有辦法代替使用sub()
嗎? 以下無效。 它僅匹配第一個匹配項,然后停止:
sub("\\b(?:red|Red)\\b", "RED", x)
#[1] "redflag flagred RED and Red"
在檢查實際模式時,它應該匹配: https : //regex101.com/r/X7DSB0/1我是否認為這與“全局標志”有關?
我也嘗試添加+
或{1,}
來獲得多個匹配項,但這都不起作用:
## using a `+` doesn't work either
sub("\\b(?:red|Red)+\\b", "RED", x)
#[1] "redflag flagred RED and Red"
## using `{1,}` doesn't work either
sub("\\b(?:red|Red){1,}\\b", "RED", x)
#[1] "redflag flagred RED and Red"
我不明白什么? 如何使用sub()
代替gsub()
進行此類操作?
gsub
的g
代表“全局”,這意味着您要告訴正則表達式引擎將替換應用於整個字符串。 另一方面, sub
只是執行它遇到的第一個替換。
因此,問題的答案是,如果您打算進行所有可能的替換,則應使用gsub
:
gsub("\\b(?:red|Red)\\b", "RED", x)
[1] "redflag flagred RED and RED"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.