Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex expression: file names that do not contain a word and matches a given pattern

I need a regex expression to check whether a file name matches the following pattern: report*.txt and does not contain the following string "car". So for report_car_as.txt, rep_as, report_tds, it should return false, and for report_abc.txt, report_sa.txt it should return true.

I have the following code lines:

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));

I dont know how to combine those 2 regex expressions. Can you help me, please?

Note: I am not allowed to use an if statement like

 if(a.matches(regex1) && a.matches(regex2));
like image 567
lucian.marcuta Avatar asked Oct 15 '25 03:10

lucian.marcuta


1 Answers

According to your requirements, you can use this regex ^report((?!.*car).*)\.txt$, where:

^report means, that your file name begins with report word

\.txt$ your file name ends with the .txt

((?!.*car).*) is content between the report and .txt, which contains any characters, except car sequence (?! is negative lookahead).

If the car word could be not just between the report and txt, you can specify it by adding the (?!.*car).* to the regex beginning, like ^(?!.*car).*report((?!.*car).*)\.txt$

like image 150
Stanislav Avatar answered Oct 17 '25 18:10

Stanislav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!