0

Essentially, I want to take a bunch of:

<Cube currency="USD" rate="1.2954"/>

And put them into a hashmap of the format:

String USD, String 1.2954

I have the following Code:

Map<String, String> list = new HashMap<String, String>();
Pattern p = Pattern.compile("<Cube\\scurrency='(.*)'\\srate='(.*)'/>");
Matcher matcher = p.matcher(currency_source);
while (matcher.find()) {
    list.put(matcher.group(1)); // PROBLEMATIC
}

I don't know how to properly add the currency and rate to the hashmap.

Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118
  • 1.your source looks like XML, so why you don't just youse an XML parser and add them aftwerwards into your map? 2. A HaspMap uses Key/Value, matcher() returns one String. – MemLeak Sep 21 '12 at 14:27

2 Answers2

3

(I see you're trying to parse XML using regex. Maybe you should consider using an XML parser instead, e.g. Is there an easier way to parse XML in Java?)

Firstly, your regex is wrong, as (.*) is too greedy. Change it to:

Pattern p = Pattern.compile("<Cube\\scurrency='([^']*)'\\srate='([^']*)'/>");

so that the ' won't be matched. Secondly, the .put() method simply takes the key and the value in its 2 arguments. So you could just use:

list.put(matcher.group(1), matcher.group(2));
Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1

A Map or HashMap works by key-value pair model, if you want to add key and value pairs where I believe currency is your key and rate your value you would do it like this,

map.put("$", matcher.group(1));

EDIT:

Try to improve your regex so that it gives you two different groups the first one being the currency type and the second group being your currency value the put it into your map

map.put(matcher.group(1), matcher.group(2));

For regex generation I use TX2RE, use it to generate correct regexes.

Arif Nadeem
  • 8,524
  • 7
  • 47
  • 78
  • The problem is that instead of the dollar sign I should put the string captured between `currency="[here]"`. I don't know how to access it. I tried matcher.group(2), but it doesn't work. – Dzhuneyt Sep 21 '12 at 14:28
  • @ColorWP.com PLEASE see I have edited my answer, your problem is that you should generate regex so that you get two logical groups one for type and other for value. – Arif Nadeem Sep 21 '12 at 14:32