Verify if String matches a format String

前端 未结 7 2229
误落风尘
误落风尘 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:49

    You can use String.matches; although you'd need to use a regular expression then, rather then the format string.

    It shouldn't be too hard to replace something like %03d with a \d{3} regex equivalent

    Example:

    "song001.mp3".matches("song\\d{3}\\.mp3") // True

    "potato".matches("song\\d{3}\\.mp3") // False

    If you really need the format string, you'll need to make a function that replaces the format with a regex equivalent, and escapes the regex reserved characters; then use the String.matches function.

提交回复
热议问题