คุณสามารถสร้างกลุ่มที่ตรงกันในนิพจน์ทั่วไปได้โดยแยกนิพจน์ด้วยวงเล็บ ตามนิพจน์ทั่วไป กลุ่มแรกจะจับคู่ตัวเลข และกลุ่มที่สองตรงกับตัวอักษรภาษาอังกฤษ −
(\\d)([A-Za-z])
กล่าวโดยย่อ คือ จะจับคู่ส่วนในสตริงอินพุตที่มีตัวเลขตามด้วยตัวอักษร
เนื่องจากนิพจน์ $1 หมายถึง Group1 และ $2 หมายถึง Group2 หากคุณแทนที่นิพจน์ทั่วไป Java ด้านบนด้วย $1 $2 ใช้วิธีการแทนที่ () (ของคลาสสตริง) ช่องว่างจะถูกเพิ่มระหว่างตัวเลขและคำในสตริงอินพุตที่กำหนดเมื่อตัวเลขตามด้วยคำ
ตัวอย่าง
import java.util.Scanner;
public class SampleTest {
public static void main( String args[] ) {
String regex = "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//String result = input.replaceAll(regex, " ");
String result = input.replaceAll( "(\\d)([A-Za-z])", "$1 $2" );
System.out.println(result);
}
} ผลลัพธ์
Enter input text: 21This 23is 56sample 99text 21 This 23 is 56 sample 99 text
ในทำนองเดียวกัน คุณสามารถเพิ่มช่องว่างระหว่างตัวเลขและตัวอักษรในข้อความที่กำหนดโดยไม่คำนึงถึงลำดับที่คุณต้องการแทนที่นิพจน์ต่อไปนี้ด้วยช่องว่าง -
(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])
ตัวอย่าง
import java.util.Scanner;
public class SampleTest {
public static void main( String args[] ) {
String regex = "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//String result = input.replaceAll(regex, " ");
String result = input.replaceAll( regex, " " );
System.out.println(result);
}
} ผลลัพธ์
Enter input text: 21This23is56sample99text 21 This 23 is 56 sample 99 text