从字符串中提取十进制数 [英] Extracting decimal numbers from a string
本文介绍了从字符串中提取十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,例如 "3.1 ml"
或 "abc 3.1 xywazw"
I have a string such as "3.1 ml"
or "abc 3.1 xywazw"
我想从这个字符串中提取"3.1"
.我在 stackoverflow 上发现了很多关于从字符串中提取数字的问题,但没有解决方案适用于十进制数字的情况.
I'd like to extract "3.1"
from this string. I have found many questions on stackoverflow about the extraction of numbers from a character string, but no solution works for the case of decimal numbers.
推荐答案
此方法使小数点和小数部分可选,并允许提取多个数字:
This approach makes the decimal point and decimal fraction optional and allows multiple numbers to be extracted:
str <- " test 3.1 test 5"
as.numeric(unlist(regmatches(str,
gregexpr("[[:digit:]]+\\.*[[:digit:]]*",str))
) )
#[1] 3.1 5.0
关于负数的问题可以通过可选的 perl 样式前瞻来解决:
The concern about negative numbers can be address with optional perl style look-ahead:
str <- " test -4.5 3.1 test 5"
as.numeric(unlist(regmatches(str,gregexpr("(?>-)*[[:digit:]]+\\.*[[:digit:]]*",str, perl=TRUE))))
#[1] -4.5 3.1 5.0
这篇关于从字符串中提取十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文