आप निम्नलिखित रेगुलर एक्सप्रेशन में से किसी का उपयोग करके दी गई स्ट्रिंग में नंबरों से मिलान कर सकते हैं −
"\\d+" या, "([0-9]+)"
उदाहरण 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractingDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter sample text: ");
String data = sc.nextLine();
// स्ट्रिंग में डिजिट्स से मिलान करने के लिए रेगुलर एक्सप्रेशन
String regex = "\\d+";
// Pattern ऑब्जेक्ट बनाना
Pattern pattern = Pattern.compile(regex);
// Matcher ऑब्जेक्ट बनाना
Matcher matcher = pattern.matcher(data);
System.out.println("Digits in the given string are: ");
while(matcher.find()) {
System.out.print(matcher.group()+" ");
}
}
}आउटपुट
Enter sample text: this is a sample 23 text 46 with 11223 numbers in it Digits in the given string are: 23 46 11223
उदाहरण 2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Just {
public static void main(String[] args) {
String data = "abc12def334hjdsk7438dbds3y388";
// डिजिट्स से मिलान करने के लिए रेगुलर एक्सप्रेशन
String regex = "([0-9]+)";
// Pattern ऑब्जेक्ट बनाना
Pattern pattern = Pattern.compile(regex);
// Matcher ऑब्जेक्ट बनाना
Matcher matcher = pattern.matcher(data);
System.out.println("Digits in the given string are: ");
while(matcher.find()) {
System.out.print(matcher.group()+" ");
}
}
}आउटपुट
Digits in the given string are: 12 334 7438 3 388