如何将识别的正则表达式项设置为字符串?



我试图在几行文本中识别两种类型的短语,day/month/month(例如:29/1)和dayday/monthmonth/yearyearyear (29/1/2022)我已经提出了匹配我的模式的匹配器:

Matcher matcherWithYear = pattern.matches((\d\d)\/(\d\d)\/(\d\d\d\d)");
Matcher matcherNoYear = pattern.matches("(\d\d)\/(\d\d)");

但是,我不知道如何将识别的短语转换成字符串。

您可以简化您的正则表达式。这是你要找的:

Pattern pattern = Pattern.compile("\b\d{1,2}/\d{1,2}(/\d{4})?\b");
String text = "blahblahblabhlah 29/1 asdasd asdasd 29/1/2022";

Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}

最新更新