簡體   English   中英

Java匹配正則表達式,然后使用第二個正則表達式格式化字符串

[英]Java match regex then format string using second regex

我試圖首先用正則表達式模式匹配字符串,然后使用第二種模式來格式化該字符串。 從我所讀的內容中,實現此目的的一種方法是使用.replaceAll() 編輯.replaceAll()並非用於此目的,請閱讀答案的注釋以進行澄清)

我創建了此功能,目的是:

  1. 匹配給定的字符串以match
  2. 使用format正則表達式格式化給定的字符串

     String match = "(^[AZ]{2}[0-9]{2}[AZ]{3}$)"; String format = "(^[AZ]{2}[0-9]{2}[*\\\\s\\\\\\\\][AZ]{3}$)"; String input = "YO11YOL" if (input.matches(match)) { return input.replaceAll(input, "??"); } 

輸出應為YO11 YOL ,在第四個字符后添加空格

這就是您想要的:不幸的是,它無法以您想要的方式完成。 但是可以使用substring來完成。

public static void main(String args[]){
    String match = "(^[A-Z]{2}[0-9]{2}[A-Z]{3}$)";
    String input = "YO11YOL";

    if (input.matches(match)) {
       String out = input.substring(0, 4) + " " + input.substring(4, 7);
       System.out.println(out);
    }

}

您可以使用兩個捕獲組 ,並從占位符 $1$2的字符串替換模式中引用它們:

String result = input.replaceFirst("^([A-Z]{2}[0-9]{2})([A-Z]{3})$", "$1 $2");

請參閱正則表達式演示和圖表:

在此處輸入圖片說明

請注意, .replaceFirst就足夠了(盡管您可以使用.replaceAll ),因為只需要執行一次替換操作(由於^$ ,正則表達式與整個字符串匹配)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM