开发者

matching string to filenames with regex (java 1.6)

I have a bunch of images with names such 开发者_开发知识库as nineDiamonds.gif and aceHearts.gif along with a "Card" class for playing card faces.

In the constructor, I want to pass a String of the card name and be able to create a JPanel with the right image. Easy enough, but I want to be able to pass things such as:

  • "9 of hearts" => nineHearts.gif
  • "9 hearts" => nineHearts.gif
  • "nine of Hearts" => nineHearts.gif
  • Integer.toString(9) + "hearts" => nineHearts.gif
  • Integer.toString(1) + "hearts" => aceHearts.gif
  • "Ace of hearts" => aceHearts.gif

I understand I can overload the constructor and match things up with a switch and what not, but what I am really after is am elegant, functional style solution, something along the lines of:

String fileName = name.replaceAll("magic regex") + ".gif";

Thanks!


One .replaceAll() is not going to be enough.

Lowercase your string. (\S+)\s*(?:of)?\s*(hearts|clubs|diamonds|spades) will parse 9 of hearts and 9hearts to ("9", "hearts"), and aceofclubs to ("ace", "clubs"). Create a map that maps "1" to "ace", ... "13" to "king"; pass first groups of the match through it. Then creation of the filename becomes trivial.


Here are some tips that should get you to a working solution:

  • Strip the word "of" using a regular expression with word boundaries (\bof\b)
  • Replace numeric strings with their respective words (can be done with a map defining the numbers (e.g. map[9] = "nine") and a for loop)
  • Use String.split() to split at word boundaries, then capatalise the all but the first word and re-join

So in the end, a regular expression alone is not the best solution as is often the case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜