Verify if String matches a format String

前端 未结 7 1764
旧巷少年郎
旧巷少年郎 2021-02-13 09:15

In Java, how can you determine if a String matches a format string (ie: song%03d.mp3)?

In other words, how would you implement the following function?

相关标签:
7条回答
  • 2021-02-13 09:58

    Since you do not know the format in advance, you will have to write a method that converts a format string into a regexp. Not trivial, but possible. Here is a simple example for the 2 testcases you have given:

    public static String getRegexpFromFormatString(String format)
    {
        String toReturn = format;
    
        // escape some special regexp chars
        toReturn = toReturn.replaceAll("\\.", "\\\\.");
        toReturn = toReturn.replaceAll("\\!", "\\\\!");
    
        if (toReturn.indexOf("%") >= 0)
        {
            toReturn = toReturn.replaceAll("%s", "[\\\\w]+"); //accepts 0-9 A-Z a-z _
    
            while (toReturn.matches(".*%([0-9]+)[d]{1}.*"))
            {
                String digitStr = toReturn.replaceFirst(".*%([0-9]+)[d]{1}.*", "$1");
                int numDigits = Integer.parseInt(digitStr);
                toReturn = toReturn.replaceFirst("(.*)(%[0-9]+[d]{1})(.*)", "$1[0-9]{" + numDigits + "}$3");
            }
        }
    
        return "^" + toReturn + "$";
    }
    

    and some test code:

    public static void main(String[] args) throws Exception
    {
        String formats[] = {"hello %s!", "song%03d.mp3", "song%03d.mp3"};
        for (int i=0; i<formats.length; i++)
        {
            System.out.println("Format in [" + i + "]: " + formats[i]);
            System.out.println("Regexp out[" + i + "]: " + getRegexp(formats[i]));
        }
    
        String[] words = {"hello world!", "song001.mp3", "potato"};
        for (int i=0; i<formats.length; i++)
        {
            System.out.println("Word [" + i + "]: " + words[i] +
                " : matches=" + words[i].matches(getRegexpFromFormatString(formats[i])));
        }
    }
    
    0 讨论(0)
提交回复
热议问题