【问题标题】:Regex expression: file names that do not contain a word and matches a given pattern正则表达式:不包含单词且匹配给定模式的文件名
【发布时间】:2016-02-09 21:28:40
【问题描述】:

我需要一个正则表达式来检查文件名是否与以下模式匹配: report*.txt 并且不包含以下字符串“car”。 所以对于report_car_as.txtrep_asreport_tds,它应该返回false,对于report_abc.txtreport_sa.txt,它应该返回真

我有以下代码行:

final File f = new File("~/home/report_fds.txt");
final String regex1 = "^((?!car).)*$";
final String regex2 = "report.*\\.txt";
System.out.println(f.getName().matches(regex2));

我不知道如何组合这 2 个正则表达式。你能帮帮我吗?

注意:我不允许使用类似的 if 语句

 if(a.matches(regex1) && a.matches(regex2));

【问题讨论】:

  • 也许,^(?!.*car).*report[^/]*\.txt$。或^.*(?!.*car)report[^/]*\.txt$。这取决于应该禁止 car 的位置。或类似^~(?:/[^/]*)*(?!.*car)report[^/]*\.txt$.

标签: java regex regex-negation


【解决方案1】:

根据您的要求,您可以使用此正则表达式^report((?!.*car).*)\.txt$,其中:

^report表示,你的文件名以report word开头

\.txt$你的文件名以.txt结尾

((?!.*car).*) 是介于report.txt 之间的内容,其中包含除car 序列以外的任何字符(?! 是负前瞻)。

如果car 单词不仅仅位于reporttxt 之间,您可以通过在正则表达式开头添加(?!.*car).* 来指定它,例如^(?!.*car).*report((?!.*car).*)\.txt$

【讨论】:

    猜你喜欢
    • 2016-01-14
    • 2021-09-13
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    相关资源
    最近更新 更多