Verify if String matches a format String

前端 未结 7 2234
误落风尘
误落风尘 2021-02-13 08:55

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:39

    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
                                                            
提交回复
热议问题