[英]gsub replace word not followed by : with word: R
I thought this would be simpler, but I have strings not followed by ':', and strings with :
inside the string.我认为这会更简单,但我的字符串后面没有':',字符串里面有:
。 I want to append :
to strings that don't end in :
, and ignore strings that have :
inside.我想 append :
到不以:
结尾的字符串,并忽略内部有:
的字符串。
words
[1] "Bajos" "Ascensor" "habs.:3"
gsub('\\b(?!:)', '\\1:', words, perl = TRUE)
[1] ":Bajos:" ":Ascensor:" ":habs:.::3:"
grep('\\W', words)
[1] 3
grep('\\w', words)
[1] 1 2 3 # ?
Desired output:所需的 output:
'Bajos:' 'Ascensor:' 'habs.:3'
sub("^([^:]*)$", "\\1:", words)
# [1] "Bajos:" "Ascensor:" "habs.:3"
or或者
nocolon <- !grepl(":", words)
words[nocolon] <- paste0(words[nocolon], ":")
words
# [1] "Bajos:" "Ascensor:" "habs.:3"
Use利用
"(\\p{L}+)\\b(?![\\p{P}\\p{S}])"
See regex proof .请参阅正则表达式证明。
EXPLANATION解释
--------------------------------------------------------------------------------
(\p{L}+) one or more letters (group #1)
--------------------------------------------------------------------------------
\b word boundary
--------------------------------------------------------------------------------
(?![\p{P}\p{S}]) no punctuation allowed on the right
--------------------------------------------------------------------------------
R code snippet : R 代码片段:
gsub("(\\p{L}+)\\b(?![\\p{P}\\p{S}])", "\\1:", text, perl=TRUE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.