简体   繁体   中英

Adding onto a java.util.regex.Pattern or Merging Them

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 (eg 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.

No, you cannot modify a compiled Pattern . You could create a new Pattern by combining the regex strings and calling Pattern.compile() again.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM