一个正则表达式,用于删除除以 # 开头的单词之外的数字

A Regex to remove digits except for words starting with #

我有一些字符串可以包含字母、数字和“#”符号。

我想删除除以“#”开头的单词之外的数字

这是一个例子:

"table9 dolv5e #10n #dec10 #nov8e 23 hello"

预期的输出是:

"table dolve #10n #dec10 #nov8e  hello"

如何使用正则表达式、stringr 或 gsub 执行此操作?

基础 R 解决方案:

unlisted_strings <- unlist(strsplit(X, "\s+"))

Y <- paste0(na.omit(ifelse(grepl("[#]", unlisted_strings),

                           unlisted_strings,

                           gsub("\d+", "", unlisted_strings))), collapse = " ")

Y 

数据:

X <- as.character("table9 dolv5e #10n #dec10 #nov8e 23 hello")

您使用 gsub 删除数字,例如:

gsub("[0-9]","","table9")
"table"

我们可以使用 strsplit 拆分您的字符串:

STRING = "table9 dolv5e #10n #dec10 #nov8e 23 hello"
strsplit(STRING," ")
[[1]]
[1] "table9" "dolv5e" "#10n"   "#dec10" "#nov8e" "23"     "hello"

我们只需要使用 gsub 遍历 STRING,仅将其应用于没有“#”的元素

STRING = unlist(strsplit(STRING," "))
no_hex = !grepl("#",STRING)
STRING[no_hex] = gsub("[0-9]","",STRING[no_hex])
paste(STRING,collapse=" ")
[1] "table dolve #10n #dec10 #nov8e  hello"

您可以在空格处拆分字符串,如果数字不以“#”开头,则从标记中删除数字并粘贴回来:

x <- "table9 dolv5e #10n #dec10 #nov8e 23 hello"
y <- unlist(strsplit(x, ' '))
paste(ifelse(startsWith(y, '#'), y, sub('\d+', '', y)), collapse = ' ')
# output 
[1] "table dolve #10n #dec10 #nov8e  hello"

如何 capturing 想要的和用空的(未捕获的)替换不需要的。

gsub("(#\S+)|\d+","\1",x)

See demo at regex101 or R demo at tio.run(我没有使用 R 的经验)

我的回答是假设 #foo bar #baz2 之间总是有空格。如果你有类似 #foo1,bar2:#baz3 4use \w(单词字符)而不是 \S(非空格)的东西。

INPUT = "table9 dolv5e #10n #dec10 #nov8e 23 hello";
OUTPUT = INPUT.match(/[^#\d]+(#\w+|[A-Za-Z]+\w*)/gi).join('');

您可以删除标志 i,因为它不区分大小写

使用此模式:[^#\d]+(#\w+|[A-Za-Z]+\w*)

[^#\d]+ = 字符以无 # 和数字开头 #\w+ = 查找#后跟数字或字母 [A-Za-z]+\w* = 查找字母后跟字母 and/or 数字 ^ | 您可以使用 \D+\S* = 查找任何字符来更改此设置,而不仅仅是当第一个字符是字母而不仅仅是后跟字母 and/or 数字时。 我没有写成 \w+\w* 因为 \w 和 = [\w\d].

一样

我尝试了 JavaScript 中的代码并且有效。 如果您不仅要匹配字母,还可以使用代码