Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a string such as "3.1 ml" or "abc 3.1 xywazw"

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
425 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...