我匹配并替换前面和后面有空格的4位数字:
str12 <- "coihr 1234 &/()= jngm 34 ljd"
sub("\\s\\d{4}\\s", "", str12)
[1] "coihr&/()= jngm 34 ljd"
Run Code Online (Sandbox Code Playgroud)
但是,每次尝试反转这个并提取数字都会失败.我想要:
[1] 1234
Run Code Online (Sandbox Code Playgroud)
有人有线索吗?
ps:我知道怎么用{stringr}来做,但我想知道是否只能用{base}来实现它.
require(stringr)
gsub("\\s", "", str_extract(str12, "\\s\\d{4}\\s"))
[1] "1234"
Run Code Online (Sandbox Code Playgroud)
regmatches(),仅在R-2.14.0之后可用,允许您"从匹配数据中提取或替换匹配的子串regexpr,gregexpr或者regexec"
以下是如何使用regmatches()提取输入字符串中的第一个空白缓冲的4位子字符串或所有此类子字符串的示例.
## Example strings and pattern
x <- "coihr 1234 &/()= jngm 34 ljd" # string with 1 matching substring
xx <- "coihr 1234 &/()= jngm 3444 6789 ljd" # string with >1 matching substring
pat <- "(?<=\\s)(\\d{4})(?=\\s)"
## Use regexpr() to extract *1st* matching substring
as.numeric(regmatches(x, regexpr(pat, x, perl=TRUE)))
# [1] 1234
as.numeric(regmatches(xx, regexpr(pat, xx, perl=TRUE)))
# [1] 1234
## Use gregexpr() to extract *all* matching substrings
as.numeric(regmatches(xx, gregexpr(pat, xx, perl=TRUE))[[1]])
# [1] 1234 3444 6789
Run Code Online (Sandbox Code Playgroud)
(请注意,numeric(0)对于不包含符合条件的子字符串的字符串,这将返回).
可以使用 来捕获正则表达式中的组()。举同样的例子
str12 <- "coihr 1234 &/()= jngm 34 ljd"
gsub(".*\\s(\\d{4})\\s.*", "\\1", str12)
[1] "1234"
Run Code Online (Sandbox Code Playgroud)