(
, )
(and many others such as +
,*
,[
,]
, .
) are special characters in regex. Therefore, it is necessary to escape them, i.e. \(
, \)
in order to specify the literal character.
However, in this case, since you obtain the pattern by concatenating f.getAbsolutePath()
, it is strongly recommended that you use Pattern.quote(String)
to make all characters in f.getAbsolutePath()
literal. It will make sure none of the character are interpreted as special character in regex.
String pattern = Pattern.quote(f.getAbsolutePath()) + "/[^/]*";
(When you print out the pattern
after applying Pattern.quote
, you may notice that it adds \Q
and \E
to the original string. It is the way to escape all characters in a long string, supported by Java regex and several other regex flavors).