Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java regex thêm khoảng trắng giữa số và chữ


Cách 1: Capture groups + replace

Regex: (\\d)([A-Za-z]) - group 1: số, group 2: chữ. Replace: $1 $2.

import java.util.Scanner;

public class SampleTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập văn bản: ");
        String input = sc.nextLine();
        String result = input.replaceAll("(\\d)([A-Za-z])", "$1 $2");
        System.out.println(result);
    }
}
Nhập văn bản: 21This 23is 56sample 99text
21 This 23 is 56 sample 99 text

Cách 2: Lookaround (hai chiều)

Regex: (?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z]) - vị trí giữa chữ/số bất kể thứ tự.

String regex = "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])";
String result = input.replaceAll(regex, " ");
// Input: 21This23is56sample99text
// Output: 21 This 23 is 56 sample 99 text

Giải thích Lookaround

  • (?<=[A-Za-z]) - positive lookbehind: trước là chữ
  • (?=[0-9]) - positive lookahead: sau là số
  • | - hoặc ngược lại (số trước, chữ sau)
  • Không consume ký tự, chỉ khớp vị trí (zero-width)

So sánh

CáchƯu điểmNhược điểm
Capture groupsĐơn giản, dễ hiểuChỉ số→chữ, không chữ→số
LookaroundHai chiều, linh hoạtPhức tạp hơn, hiệu năng kém chút