I am trying to write a simple regular expression to identify all filenames in a list which end with ".req.copied" extension. The code I am using is given below
public class Regextest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String test1=new String("abcd.req.copied");
if(test1.matches("(req.copied)?")) {
System.out.println("Matches");
}
else
System.out.println("Does not Match");
}
}
The regex tests ok in online regex testers but does not function in the program. I have tried multiple combinations (like splitting req and copied into two regexes, or literal matching of the dot character) but nothing works (even the simplest regex of (reg)? returned a "Does not Match" output). Please let me know how to tackle this.
Main problem with matches
here is that it requires from regex to match entire string. But in your case your regex describes only part of it.
If you really want to use matches
here your code could look more like
test1.matches(".*\\.req\\.copied")
.
represents any character (except line separators like \r
) so if you want it to represent only dot you need to escape it like \.
(in string we need to write it as "\\."
because \
has also special meaning there - like creating special characters \r
\n
\t
and so on - so it also requires escaping via additional \
)..*
will let regex accept any characters before .req.copied
But in your case you should simply use endsWith
method
test1.endsWith(".req.copied")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With