Verify if String matches a format String

前端 未结 7 1772
旧巷少年郎
旧巷少年郎 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:47

    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.

提交回复
热议问题