regex 匹配多个不同单词的正则表达式

o4tp2gmn  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(195)

我有以下类型的词要匹配:
请输入您的姓名和电话号码。
您的位置:凡人谷知道〉娱乐城〉
我想匹配评分前后的所有单词,但也要匹配一个日期可变的电影文件
我试过下面的,但是不起作用。

.*(ratings|movie)*.(txt|doc){d{4}\d{2}\d{2}}
xuo3flqw

xuo3flqw1#

如果我理解正确的话,要想以你想要的方式解析字符串,我认为用RegEx是相当困难的,但是你可以这样解析它:

String str = "anyword_ratings_.anyword_anyword.doc.20221111 movie.txt.20221111";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
str = str.trim();
String[] parts = str.split("\\s+");
String firstPart = parts[0];
String secondPart = parts[1];
   
String beforeRatings = firstPart.substring(0, firstPart.indexOf("ratings")).replace("_", " ").trim();
   
String afterRatings = firstPart.substring(firstPart.indexOf("ratings") + 7, firstPart.lastIndexOf(".")).trim();
while (afterRatings.startsWith("_") || afterRatings.startsWith(".")) {
    afterRatings = afterRatings.substring(1);
}
   
String ratingDateString = firstPart.substring(firstPart.lastIndexOf(".") + 1);
LocalDate ratingDate = LocalDate.parse(ratingDateString, dtf);
   
String movieFile = secondPart.substring(0, secondPart.lastIndexOf("."));
String movieDateString = secondPart.substring(secondPart.lastIndexOf(".") + 1);
   
LocalDate movieDate = LocalDate.parse(movieDateString, dtf);
   
// Display variables in Console Window:
System.out.println("Before Ratings: " + beforeRatings);
System.out.println("After Ratings:  " + afterRatings);
System.out.println("Ratings Date:   " + ratingDate + " (LocalDate Type \"yyyy-MM-dd\")");
System.out.println("Movie File:     " + movieFile);
System.out.println("Movie Date:     " + movieDate + " (LocalDate Type \"yyyy-MM-dd\")");

控制台窗口将显示:

Before Ratings: anyword
After Ratings:  anyword_anyword.doc
Ratings Date:   2022-11-11 (LocalDate Type "yyyy-MM-dd")
Movie File:     movie.txt
Movie Date:     2022-11-11 (LocalDate Type "yyyy-MM-dd")

相关问题