簡體   English   中英

如何將字符串中的所有實數(甚至是負數和科學數)提取到數字向量中?

[英]How do I extract all real numbers (even negative and scientific) from a string into a numeric vector?

我正在使用 R 編程語言工作,希望能在制定正則表達式方面提供一些幫助。

我有一個設置,我接受來自用戶的數字列表作為字符串,並且我想將字符串中的所有數字提取到數字向量中。 我已通知用戶向我提供以逗號分隔的數字。 但我不能指望用戶尊重這一點。 因此,即使它們用空格或分號或其他奇怪的東西分隔,我也想提取這些數字。

我希望能夠從字符串中提取所有實數,即使數字是負數(例如 -5)或包含小數(例如 5.5)或采用科學記數法(例如 5.5e-5、5.5E-5 , 5.5e+5, 5.5E+5, 5.5e5, 5.5E5)

我正在閱讀有關類似問題的論壇,並確定了可以從字符串中提取數字的正則表達式,但我意識到它不適用於負數、小數或科學記數法。 我希望能夠處理所有。

Using this regular expression I am able to extract real whole numbers from a string separated by spaces or commas or even semi-colons. 

    # Using this string works 
    this_string = "1, 2  3, 5, 7, 10, 11, 12; 18" 
    extracted_numbers = as.numeric(regmatches(this_string, gregexpr("[0-9]+", this_string))[[1]])
    print(extracted_numbers)

提取結果:[1] 1 2 3 5 7 10 11 12 18

但同樣的正則表達式不適用於這個更復雜的負數、科學記數法和小數字符串。

this_string = "-1, 0, 5e-1 ; 7E-1, 2  3.0, 4, 5.33e+2"

提取結果:[1] 1 0 5 1 7 1 2 3 0 4 5 33 2

從字符串中正確提取數字應該產生:

期望的提取結果:[1] -1.0 0.0 0.5 0.7 2.0 3.0 4.0 533.0

非常感謝你的幫助。

編輯:我剛剛找到了一個可行的解決方案:

this_string = "-1, 0, 5e-1 ; 7E-1, 2  3.0, 4, 5.33e+2" 
extracted_numbers = as.numeric(regmatches(this_string, gregexpr("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?", this_string))[[1]])
print(extracted_numbers)

用戶 Wojciech Sobala 在此問題中使用上述正則表達式提供了答案: Extracting decimal numbers from a string

謝謝沃伊切赫。

這是你需要的嗎?

library(tidyverse)
data.frame(this_string) %>%
   mutate(
          # clean-up strings and convert to numeric:
          this_string = lapply(
            # split strings:
            str_split(this_string, "(?<=\\d{1,10})(?=\\s(?!;))|(),|\\s;"),
            # apply `as.numeric`:
            as.numeric)
          )
                                this_string
1 -1.0, 0.0, 0.5, 0.7, 2.0, 3.0, 4.0, 533.0

如果您希望將結果作為向量:

lapply(str_split(this_string, "(?<=\\d{1,10})(?=\\s(?!;))|(),|\\s;"), as.numeric)

數據:

this_string = "-1, 0, 5e-1 ; 7E-1, 2  3.0, 4, 5.33e+2"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM