我尝试首先将字符串与正则表达式模式匹配,然后使用第二个模式来格式化该字符串。根据我所读到的内容,实现此目的的一种方法是使用 .replaceAll()
(edit: .replaceAll()
不用于此目的,请阅读答案的评论以进行澄清)
我创建了这个函数,其目的是:
- 将给定字符串与
匹配
使用
format
正则表达式格式化给定字符串String match = "(^[A-Z]{2}[0-9]{2}[A-Z]{3}$)"; String format = "(^[A-Z]{2}[0-9]{2}[*\\s\\\\][A-Z]{3}$)"; String input = "YO11YOL" if (input.matches(match)) { return input.replaceAll(input, "??"); }
输出应为 YO11 YOL
,并在第四个字符后添加空格
最佳答案
这就是您想要的:不幸的是,它无法按照您想要的方式完成。但可以使用子字符串来完成。
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);
}
}
关于Java匹配正则表达式,然后使用第二个正则表达式格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54914876/