提取字符串中的数字和句点。

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

Extract only digits and full stop from string

问题

我只想保留数字和小数点。是否有解决方案?感谢您的帮助。

英文:

I have following strings :
x <- c("3 333.33!", "1 002 22??", "232.23x")
I only want to keep numbers and dots.

is there a solution?

Thanks for your help

答案1

得分: 2

We could just extract any digits and full stops and then collapse the string again.

library(stringr)
sapply(str_extract_all(x, "[:digit:]|\\."), function(x) str_c(x, collapse=""))

"3333.33" "100222" "232.23"

英文:

We could just extract any digits and full stops and then collapse the string again.

library(stringr)
sapply(str_extract_all(x, "[:digit:]|\\."), function(x) str_c(x, collapse=""))

"3333.33" "100222"  "232.23"

答案2

得分: 2

删除空格(正则表达式 " +" 表示“一个或多个空格”),然后调用 readr::parse_number(),它会忽略除了 .- 之外的字母字符/标点符号。

x |> stringr::str_remove(" +") |> readr::parse_number()
英文:

Remove whitespace (regex " +" means "one or more spaces") and then call readr::parse_number(), which ignores alphabetic characters/punctuation other than .-

x |> stringr::str_remove(" +") |> readr::parse_number()

答案3

得分: 1

在基本的 R 语言中:

gsub("[^0-9.]", "", x)
[1] "3333.33" "100222"   "232.23" 

如果你需要它们作为数字:

```R
as.numeric(gsub("[^0-9.]", "", x))
[1]  3333.33 100222.00   232.23
英文:

in base R:

gsub("[^0-9.]", "", x)
[1] "3333.33" "100222"  "232.23" 

if you need them as numeric:

as.numeric(gsub("[^0-9.]", "", x))
[1]   3333.33 100222.00    232.23

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

发表评论

匿名网友

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

确定