英文:
How to extract a string between two points and a dot
问题
我想提取冒号后和点号前的数字序列,即22334455。我尝试使用gsub("\\:*", "", 11:22334455.CEL)
,但结果如下:
11216803.CEL
如何修复gsub
函数以仅获取22334455?
英文:
I have the following string in R:
11:22334455.CEL
I would like to extract only the number series after : and before ., that means
22334455
I was trying with gsub("\\:*", "", 11:22334455.CEL)
, but I got the following result:
11216803.CEL
How could I fix the gsub
function to get only 22334455
?
Thank you!
答案1
得分: 1
你可以使用正则表达式捕获组(括号 (\\d+)
)来捕获你想要的内容。
sub(".*:(\\d+)\\..*", "\", "11:22334455.CEL")
[1] "22334455"
英文:
You can use a regex capture group (the parentheses (\\d+)
) to capture what you want.
sub(".*:(\\d+)\\..*", "\", "11:22334455.CEL")
[1] "22334455"
答案2
得分: 0
gsub(".*:|\\..*", "", "11:22334455.CEL")
# [1] "22334455"
英文:
You can remove characters before ':'
and after '.'
gsub(".*:|\\..*", "", "11:22334455.CEL")
# [1] "22334455"
答案3
得分: 0
使用stringr
的str_extract
与group
。
\\d+
用于检测一个或多个数字,这里在大括号内定义了捕获组,位于:
和\\.
(转义的句点)之间。
library(stringr)
str_extract("11:22334455.CEL", ":(\\d+)\\.", group = 1)
[1] "22334455"
英文:
Using stringr
s str_extract
with group
.
\\d+
detects one or more digits, here between :
and \\.
(escaped period) within braces that define the capture group.
library(stringr)
str_extract("11:22334455.CEL", ":(\\d+)\\.", group = 1)
[1] "22334455"
答案4
得分: 0
使用base R
中的trimws
函数:
trimws("11:22334455.CEL", whitespace = ".*:|\\..*")
[1] "22334455"
英文:
Using trimws
from base R
trimws("11:22334455.CEL", whitespace = ".*:|\\..*")
[1] "22334455"
答案5
得分: 0
你可以使用 str_extract
与正向后顾 (?<=:)
来确保匹配仅从冒号之后开始,以及正向先行 (?=\\.)
来确保匹配后必须跟着一个 .
:
str_extract("11:22334455.CEL", "(?<=:)\\d+(?=\\.)")
[1] "22334455"
英文:
You can use str_extract
with look-behind (?<=:)
to assert that the match only starts after the colon, and look-ahead (?=\\.)
to assert that the match must be followed by a .
:
str_extract("11:22334455.CEL", "(?<=:)\\d+(?=\\.)")
[1] "22334455"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论