在R语言中从字符向量提取有效数字的正则表达式解决方案
Hey there, let's get this sorted for you! The issue with your initial regex attempt is probably the syntax differences in how R handles regular expressions—we don't use the leading/trailing / like in JavaScript, and escape characters need double backslashes.
Here's exactly what you need to pull out those valid numbers:
The Correct Regular Expression
We need a regex that matches full strings representing valid numbers, with no extra spaces or non-digit characters. Here's the pattern tailored for R:
"^-?(0|[1-9]\\d*)(\\.\\d+)?$"
Let's break down what each part does:
^and$: Anchor the match to the start and end of the string, so we only match entirely valid numbers (no extra characters like "4h" slip through)-?: Matches an optional leading negative sign0|[1-9]\\d*: Matches a valid integer part—either a single0, or a non-zero digit followed by any number of digits (prevents leading zeros like "04" if that's a concern)(\\.\\d+)?: Matches an optional decimal part—requires a dot immediately followed by one or more digits, which excludes "7. 5" (since there's a space after the dot)
Applying the Regex in R
You can use either base R or the tidyverse's stringr package to filter your vector.
Base R Approach
# Your original vector vec <- c("hi", "4", "-21", "6.5", "7. 5", "-2.2", "4h") # Filter using grepl() valid_numbers <- vec[grepl("^-?(0|[1-9]\\d*)(\\.\\d+)?$", vec)] # Check the result valid_numbers # Output: [1] "4" "-21" "6.5" "-2.2"
Tidyverse (stringr) Approach
If you prefer cleaner syntax, str_subset() does the filtering in one step:
library(stringr) valid_numbers <- str_subset(vec, "^-?(0|[1-9]\\d*)(\\.\\d+)?$") valid_numbers # Same result as above
This will exactly give you the output you're looking for, excluding invalid entries like "hi", "7. 5", and "4h".
内容的提问来源于stack exchange,提问作者Williams86

