正则表达式匹配不是 4 位数字的所有内容 [英] Regex matching everything that's not a 4 digit number
本文介绍了正则表达式匹配不是 4 位数字的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我匹配并替换前后为空格的 4 位数字:
I match and replace 4-digit numbers preceded and followed by white space with:
str12 <- "coihr 1234 &/()= jngm 34 ljd"
sub("\\s\\d{4}\\s", "", str12)
[1] "coihr&/()= jngm 34 ljd"
但是,每次尝试反转它并提取数字都会失败.我要:
but, every try to invert this and extract the number instead fails. I want:
[1] 1234
有人知道吗?
ps:我知道如何用 {stringr} 做到这一点,但我想知道是否可以只用 {base} ..
ps: I know how to do it with {stringr} but am wondering if it's possible with {base} only..
require(stringr)
gsub("\\s", "", str_extract(str12, "\\s\\d{4}\\s"))
[1] "1234"
推荐答案
可以使用 ()
在正则表达式中捕获组.以同样的例子
It's possible to capture group in regex using ()
. Taking the same example
str12 <- "coihr 1234 &/()= jngm 34 ljd"
gsub(".*\\s(\\d{4})\\s.*", "\\1", str12)
[1] "1234"
这篇关于正则表达式匹配不是 4 位数字的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文