r - 在正则表达式 R 中编写特殊字符列表

标签 r regex

我正在尝试在正则表达式(Rstudio)中编写一个特殊字符列表,但它不适用于一两个。

我的列表是:“/\? * : [ ]”

例如:

library(tidyverse)

a <- "test:e?xample"

str_replace_all(a, "[/ \ ? * : [ ]]", "_")

[1] Output : "test_e_xample"

它有效!

但使用“[”则不然

a <- "test:e[xample"

str_replace_all(a, "[/ \ ? * : [ ]]", "_")

[1] Output : "test_e[xample"

最佳答案

在基本 R 中,在字符类中,元字符 "]" 必须位于第一个。

a <- "test:e?xample"
b <- "test:e[xample"

gsub("[][/\\?*:]", "_", a)
#> [1] "test_e_xample"

gsub("[][/\\?*:]", "_", b)
#> [1] "test_e_xample"

创建于 2022 年 10 月 3 日 reprex v2.0.2

关于r - 在正则表达式 R 中编写特殊字符列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73938687/

相关文章:

r - 如何在R中计算两个数据帧之间的Jaccard相似度

r - H2o 的交叉验证指标

javascript - 拆分正则表达式数字

php - 正则表达式有助于匹配多个字母

正则表达式中的 MySQL 和单词边界

r - all.moments 功能奇怪的结果

r - 根据一定条件选择逻辑向量元素

r - 如何在双 y 轴 ggplot 中使用构面

regex - 为什么 Unicode 字符 'DOUBLE LOW-9 QUOTATION MARK' (U+201E) 不是引号?

php - 使用正则表达式分隔本地、youtube 或 vimeo 视频