คุณสามารถจับคู่ตัวเลขในสตริงที่กำหนดได้โดยใช้นิพจน์ปกติใดนิพจน์หนึ่งต่อไปนี้:
“\\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