Java Online Compiler
Example: SumNumbersInStringByRegex in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// SumNumbersInStringByRegex import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String inputString = "I have 10 apples, 5 bananas, and 2 dozens of grapes, costing $15 total."; int sum = 0; // Step 1: Define the regular expression pattern to find one or more digits Pattern pattern = Pattern.compile("\\d+"); // Step 2: Create a Matcher object to find matches in the input string Matcher matcher = pattern.matcher(inputString); // Step 3: Loop while the matcher finds occurrences of the pattern while (matcher.find()) { // Step 4: Extract the matched sequence (which is a number string) String numberStr = matcher.group(); // Step 5: Convert the number string to an integer and add to sum sum += Integer.parseInt(numberStr); } System.out.println("The original string is: \"" + inputString + "\""); System.out.println("Sum of numbers: " + sum); } }
Output
Clear
ADVERTISEMENTS