提取两个点和一个句点之间的字符串。

huangapple go评论77阅读模式
英文:

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

使用stringrstr_extractgroup

\\d+用于检测一个或多个数字,这里在大括号内定义了捕获组,位于:\\.(转义的句点)之间。

library(stringr)

str_extract("11:22334455.CEL", ":(\\d+)\\.", group = 1)
[1] "22334455"
英文:

Using stringrs 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 (?&lt;=:) 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(&quot;11:22334455.CEL&quot;, &quot;(?&lt;=:)\\d+(?=\\.)&quot;)
[1] &quot;22334455&quot;

huangapple
  • 本文由 发表于 2023年3月3日 23:42:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定