用于删除模式“[0-9]g”的正则表达式

Sha*_*aze 7 regex r

我有以下示例数据集:

XYZ 185g
ABC 60G
Gha 20g
Run Code Online (Sandbox Code Playgroud)

如何删除字符串"185g", "60G", "20g"而不意外删除主单词中的字母 g 和 G?我尝试了下面的代码,但它也替换了主要单词中的字母。

a <- str_replace_all(a$words,"[0-9]"," ")
a <- str_replace_all(a$words,"[gG]"," ")
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 10

你需要将它们组合成类似的东西

a$words <- str_replace_all(a$words,"\\s*\\d+[gG]$", "")
Run Code Online (Sandbox Code Playgroud)

\s*\d+[gG]$则表达式匹配

  • \s*- 零个或多个空格
  • \d+- 一位或多位数字
  • [gG]-g或者G
  • $- 字符串末尾。

如果您可以将这些字符串放在字符串中,而不仅仅是在末尾,则可以使用

a$words <- str_replace_all(a$words,"\\s*\\d+[gG]\\b", "")
Run Code Online (Sandbox Code Playgroud)

其中$被替换为 a \b,单词边界。

为了忽略大小写,

a$words <- str_replace_all(a$words, regex("\\s*\\d+g\\b", ignore_case=TRUE), "")
Run Code Online (Sandbox Code Playgroud)