Reputation: 3055
I'm holding filename format data in a Pattern
object. For example: _\\d+x\\d+\\.png
. In my setup, this would denote icons of different sizes (e.g. icon_16x16.png
, icon_48x48.png
and so on).
I have a method that compares an actual filename with the given pattern; however, a base name must also be provided (in my example, this would be "icon"):
public boolean matches(String filename, String baseName) {
if (!IOCase.SYSTEM.checkStartsWith(filename, baseName)) {
return false;
}
return format.matcher(filename.replaceFirst(baseName, "")).matches();
}
What I'm doing here is first checking if filename
starts with the base name. If so, the base name is stripped from the filename string so that it can be compared with the Pattern
object (format
).
I know I could do return filename.matches(Pattern.quote(baseName) + format.pattern())
, but I'm wondering if there's a better, hopefully more programmatic way of doing this.
To be precise, I want to know if it's possible to add onto a java.util.regex.Pattern
or merge two of them without dealing with their underlying string representations.
Upvotes: 0
Views: 674
Reputation: 34367
Find below a sample code using pattern/matcher/group without any string manipulation:
If prefix is word chars only
Pattern p = Pattern.compile("(\\w+)(_\\d+x\\d+\\.png)");
Matcher m = p.matcher("icon1_16x16.png");
String baseName = "icon";
//If match found, m.group(1) returns the prefix of `_..x..png`
if(m.find() && baseName.equals(m.group(1))){
System.out.println("Match Found");
}else{
System.out.println("Match Not Found");
}
If prefix can be any character, then use regex as (.+)(_\\d+x\\d+\\.png)
Upvotes: 1
Reputation: 86774
No, you cannot modify a compiled Pattern
. You could create a new Pattern
by combining the regex strings and calling Pattern.compile()
again.
Upvotes: 1