![](/img/trans.png)
[英]Using Regex in String.matches in java to match a date format
[英]Java match regex then format string using second regex
我試圖首先用正則表達式模式匹配字符串,然后使用第二種模式來格式化該字符串。 從我所讀的內容中,實現此目的的一種方法是使用.replaceAll()
( 編輯 : .replaceAll()
並非用於此目的,請閱讀答案的注釋以進行澄清)
我創建了此功能,目的是:
match
使用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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.