Phương thức replaceAll() của String nhận 2 string: regex và replacement string, thay thế giá trị match bằng replacement.
Regex match leading zeros:
^0+(?!$)
Để xóa leading zeros, truyền regex này làm tham số 1 và “” làm tham số 2.
Ví dụ
Chương trình đọc integer từ user vào String, xóa leading zeros dùng Regular expressions.
import java.util.Scanner; public class LeadingZeroesRE { public static String removeLeadingZeroes(String str) { String strPattern = "^0+(?!$)"; str = str.replaceAll(strPattern, ""); return str; } public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter an integer: "); String num = sc.next(); String result = LeadingZeroesRE.removeLeadingZeroes(num); System.out.println(result); } }
Kết quả
Enter an integer: 000012336000 12336000