我需要为给定的一组字符串(即一组日期)动态创建一个正则表达式。
String dates[] = {"25/11/1995", "26/11/1995", "27/11/1995", "28/11/1995","29/11/1995"};
因此,正则表达式必须生成为2[5-9]/11/1995
如何实现Java 6?
答案 0 :(得分:0)
这样的事情会让你走吗?
import java.util.ArrayList;
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
// Assume all data is dates
String dates[] = {"25/11/1995", "26/11/1995", "27/11/1995", "28/11/1995","29/11/1995"};
// Determine the delimeter
String delimeter = String.valueOf(dates[0].replaceAll("\\d", "").charAt(0));
// Separate out the days, months, and years distictively
ArrayList<String> days = new ArrayList<String>();
ArrayList<String> months = new ArrayList<String>();
ArrayList<String> years = new ArrayList<String>();
for (String date : dates) {
String[] pieces = date.split(delimeter);
if (!days.contains(pieces[0])) {
days.add(pieces[0]);
}
if (!months.contains(pieces[1])) {
months.add(pieces[1]);
}
if (!years.contains(pieces[2])) {
years.add(pieces[2]);
}
}
// Generate regex
System.out.print((days.size() > 1) ? "(" + String.join("|", days) + ")" : days.get(0));
System.out.print(delimeter.contentEquals("/") ? "\\" + delimeter : delimeter);
System.out.print((months.size() > 1) ? "(" + String.join("|", months) + ")" : months.get(0));
System.out.print(delimeter.contentEquals("/") ? "\\" + delimeter : delimeter);
System.out.print((years.size() > 1) ? "(" + String.join("|", years) + ")" : years.get(0));
}
}
结果:
(25|26|27|28|29)\/11\/1995
我知道它没有提供您在问题中发布的确切正则表达式,但这是有效的正则表达式。
我在Regex101进行了测试
要确切地获得所需的内容,只需使生成正则表达式更智能即可识别序列。