替换与正则表达式模式匹配的字符串开头的每个单个字符 [英] Replace every single character at the start of string that matches a regex pattern
本文介绍了替换与正则表达式模式匹配的字符串开头的每个单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想替换匹配特定模式的字符串中的每个单个字符.取以下字符串
I want to replace every single character in a string that matches a certain pattern. Take the following string
mystring <- c("000450")
我想将所有单个零匹配到第一个非零元素.我尝试过类似的
I want to match all single zeros up to the first element that is non-zero. I tried something like
gsub("^0[^1-9]*", "x", mystring)
[1] "x450"
此表达式用单个x
替换所有前导零.但是,我想用xxx
替换所有三个前导零.首选结果将是
This expression replaces all the leading zeros with a single x
. But instead, I want to replace all three leading zeros with xxx
. The preferred result would be
[1] "xxx450"
有人可以帮我吗?
推荐答案
您可以使用
mystring <- c("000450")
gsub("\\G0", "x", mystring, perl=TRUE)
## => [1] "xxx450"
请参见 regex演示和 \\G0
正则表达式在字符串的开头与0
匹配,并且仅在成功匹配之后出现的任何0
.
The \\G0
regex matches 0
at the start of the string, and any 0
that only appears after a successful match.
详细信息
-
\G
-匹配(断言")字符串开头或匹配成功后位置的锚点 -
0
-一个0
字符.
\G
- an anchor that matches ("asserts") the position at the start of the string or right after a successful match0
- a0
char.
这篇关于替换与正则表达式模式匹配的字符串开头的每个单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文