技术问询:合并正则表达式并直接移除货币符号与逗号提取数字
Absolutely! You can tweak your code to get the target numeric value in one go, skipping the manual comma removal step. Here are a few practical approaches:
Method 1: Two-step replaceAll (Simple & Readable)
This approach breaks the problem into easy-to-understand steps: first strip out currency symbols and other non-essential characters, then remove commas.
String str = "Fr.-145,000.01"; // Step 1: Remove everything except digits, negative sign, decimal point, and commas String cleanedSymbols = str.replaceAll("[^0-9\\-\\.,]", ""); // Step 2: Remove all commas from the remaining string String finalResult = cleanedSymbols.replaceAll(",", ""); System.out.println(finalResult); // Output: -145000.01
Method 2: Single replaceAll (One-step Cleanup)
If you prefer to do it in a single line, you can use a regex that matches both currency symbols and commas, replacing them all with empty strings in one pass.
The regex [^0-9\\-.]|, targets two types of characters:
- Any character that isn't a digit, negative sign, or decimal point (this catches currency symbols like
Fr.) - Commas, which we want to remove regardless of their position
String str = "Fr.-145,000.01"; String finalResult = str.replaceAll("[^0-9\\-.]|,", ""); System.out.println(finalResult); // Output: -145000.01
Method 3: Adjust Your Original Group Matching
If you want to stick with your initial pattern-matching approach, you can modify it to first capture the numeric string (including commas) and then strip out commas from the captured group:
String str = "Fr.-145,000.01"; String pattern = "^[^0-9\\-]*([0-9\\-\\.,]*?)[^0-9\\-]*$"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(str); if(m.matches()) { // Remove commas from the captured group String finalResult = m.group(1).replaceAll(",", ""); System.out.println(finalResult); // Output: -145000.01 }
Recommendation
Methods 1 and 2 are generally better choices because they're more concise, easier to maintain, and avoid the complexity of dealing with capture groups for this use case.
内容的提问来源于stack exchange,提问作者X.walt

