Java中从字符串提取Double值的问题及代码优化需求
Hey there! I see the issue with your current code—right now, you're only keeping digits (0-9) by replacing everything else, but that strips out decimal points (and would miss negative signs if they were present), so values like 4.5 get mangled into 45 which isn't useful for Double types. Let's fix this with two straightforward solutions.
Why Your Current Code Fails
Your line numbers=str.replaceAll("[^0-9]", "...") uses a regex that only matches digits. But Double values can include:
- Decimal points (
.) - Optional negative signs (
-)
So this approach destroys the structure of valid Double numbers.
Solution 1: Use Regex to Match Full Double Values
We can write a regex that specifically targets valid Double formats, then extract and parse each match. Here's the updated code:
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; public class mine { public static void main(String[] args) throws Exception { Scanner SC = new Scanner(System.in); System.out.print("Enter string that contains numbers: "); String str = SC.nextLine(); // Regex to match integers, decimals, and negative Doubles Pattern doublePattern = Pattern.compile("-?\\d+\\.?\\d*|\\d*\\.?\\d+"); Matcher matcher = doublePattern.matcher(str); System.out.println("Extracted Double values:"); while (matcher.find()) { try { double extractedValue = Double.parseDouble(matcher.group()); System.out.println(extractedValue); } catch (NumberFormatException e) { // This should rarely happen with our regex, but just in case System.out.println("Skipping invalid entry: " + matcher.group()); } } } }
Regex Breakdown
-?: Matches an optional negative sign\d+\.?\d*: Matches numbers with an integer part (like4,4.5)|: Acts as an OR operator\d*\.?\d+: Matches numbers that start with a decimal (like.5, though this is less common but still valid for Doubles)
Solution 2: Leverage Scanner's Built-in Number Detection
Java's Scanner can automatically recognize numeric values if we set the right delimiter. Instead of writing complex regex, we can tell it to split the string on any character that isn't part of a Double:
import java.util.Scanner; public class mine { public static void main(String[] args) throws Exception { Scanner SC = new Scanner(System.in); System.out.print("Enter string that contains numbers: "); String str = SC.nextLine(); // Split the string on any character that's not a digit, decimal, or negative sign Scanner numberScanner = new Scanner(str); numberScanner.useDelimiter("[^-0-9.]"); System.out.println("Extracted Double values:"); while (numberScanner.hasNextDouble()) { double extractedValue = numberScanner.nextDouble(); System.out.println(extractedValue); } numberScanner.close(); } }
How This Works
useDelimiter("[^-0-9.]") sets all non-numeric characters (like parentheses, commas, spaces, semicolons) as separators. The Scanner then uses its built-in logic to pick out valid Double values directly—no manual parsing needed!
Testing with Your Input
If you enter your test string r ( 4.5, 1.0 ) 10.5 7 ;, both solutions will output:
4.5 1.0 10.5 7.0
内容的提问来源于stack exchange,提问作者Pape Traore

