Extract Numbers from String in Java: 2 Methods
In Java, you can use regular expressions or loop through strings to extract numbers.
- Design or arrangement
- One who matches
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "abc123def456";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String number = matcher.group();
System.out.println(number);
}
}
}
- Check if the character is a digit.
public class Main {
public static void main(String[] args) {
String str = "abc123def456";
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
sb.append(c);
}
}
String numbers = sb.toString();
System.out.println(numbers);
}
}
The choice between these two methods for extracting numbers from a string depends on the specific requirements and format of the string.