删除单词和数字之间的空格

时间:2017-01-16 09:26:48

标签: r regex

this question的启发。

我们如何组合单词和由字符串中的空格分隔的数字。

例如

There is a cooling problem in the component tx 313
leakage found in irc 256, fixed by replacement
Roasted cable in cpt trx235

结果应为

There is a cooling problem in the component tx313
leakage found in irc256, fixed by replacement
Roasted cable in cat trx235

我是正则表达式的新手,所以无法想办法做到这一点

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

text=c("There is a cooling problem in the component tx 313","leakage found in irc 256, fixed by replacement",
       "Roasted cable in cpt trx235","word 123 456") 

gsub("(?<=[a-z]) (?=\\d)","",text,perl = T)
[1] "There is a cooling problem in the component tx313" "leakage found in irc256, fixed by replacement"    
[3] "Roasted cable in cpt trx235"                       "word123 456" 

(?<=[a-z])积极的背后检查,以确定在需要更换之前是否有信件 我们要删除的内容,空格 (?=\\d)肯定前瞻以检查空格后面是数字。

答案 1 :(得分:0)

我们也可以使用str_replace

library(stringr)
str_replace_all(text, "(?<=[[:alpha:]]) (?=\\d+)", "")
#[1] "There is a cooling problem in the component tx313" "leakage found in irc256, fixed by replacement"     "Roasted cable in cpt trx235"                      
#[4] "word123 456"                                      
相关问题