Verify if String matches a format String

前端 未结 7 1789
旧巷少年郎
旧巷少年郎 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
                                                            
提交回复
热议问题