in a text file I have following text.
add device 1: /dev/input/event7
name: "evfwd"
add device 2: /dev/input/event6
name: "aev_abs"
add device 3: /dev/input/event5
name: "light-prox"
add device 4: /dev/input/event4
name: "qtouch-touchscreen"
add device 5: /dev/input/event2
name: "cpcap-key"
add device 6: /dev/input/event1
name: "accelerometer"
add device 7: /dev/input/event0
name: "compass"
add device 8: /dev/input/event3
name: "omap-keypad"
What i need to do is that for each name element i need to extract the corresponding event number and put them on a hashmap.
for example from the text we see that name evfwd is linked with event7, so the hashmap will look like this
<"evfwd", 7>
similarly
<"compass", 0>
How can I efficiently parse the text and build a hashmap like that in java?
You should probably use a regex (regular expression) to parse out the info. To use a regex, look at the Pattern and Matcher classes, here’s an example:
You can then call matcher.find() to set the matchers contents to the next match (it returns true if it found another one, false if it hit the end).
You need a regex with what are called capture groups, basically whenever you put ( ) around something in a regex, you can call
matcher.group(index)to find the contents of those ( ) (it should be noted that .group(0) returns the whole thing, .group(1) contents of 1st ( ), etc.)Here’s a regex I just made that should work for you:
add device \d*?: /dev/input/event(\d*?)\n name: \"(.*?)\"This says in english:
add device [some number]: /dev/input/event[some number, capture group #1]\n name: \"[some string, capture group #2]\"To get it’s event number, call
Integer.parseInt(matcher.group(1))and to get it’s name, callmatcher.group(2).Tell me if anything fails, hope I helped 🙂