Reputation: 8709
I have string which will be in the format of
<!-- accountId="123" activity="add" request="add user" -->
Number of parameters and the order is random.
I need to get the value of request, I need to parse the add user text from the string. What is the best way to do this in Java?
Upvotes: 1
Views: 256
Reputation: 156612
You could parse it using regular expressions, something like this:
public static Map<String, String> parse(String s) {
Map<String, String> map = new HashMap<String, String>();
Pattern p = Pattern.compile("(\\w+)\\s*=\\s*\"(.*?)\"");
Matcher m = p.matcher(s);
while (m.find()) {
map.put(m.group(1), m.group(2));
}
return map;
}
With example usage:
String s = "<!-- accountId=\"123\" activity=\"add\" request=\"add user\" -->";
Map<String, String> m = parse(s);
// m => {accountId=123, request=add user, activity=add}
m.get("request"); // => "add user"
If you need to retain the ordering of the attributes you could use a LinkedHashMap or TreeMap, for example.
Upvotes: 1
Reputation: 2691
I'm mostly experienced with Python regular expressions, but the Java syntax appears to be the same. Perhaps strip off the '' from either end, then iterate through the key-value pairs with a regex like
'\s?([\w ]+)="([\w ]+)"\s?(.*?)'
(Assuming the keys and values consist only of alphanumeric characters, spaces, and underscores; otherwise, you might substitute the \w's with other sets of characters) The three groups from this match would be the next key, the next value, and the rest of the string, which can be parsed in the same way until you find what you need.
Upvotes: 0
Reputation: 37019
If you just need the value of "request", the fastest way to do that would be:
void getRequest(String str) {
int start = str.indexOf("request=\"");
if (start != -1) {
start += 9; // request="
end = str.indexOf('"', start);
if (end != -1) {
return str.substring(start, end);
}
}
// not found
return null;
}
Upvotes: 0
Reputation: 1654
A hint to keep it simple: not try to parse all in one go. For instance, first try to retrieve the raw key-value pairs like 'activity="add"'. Then continue from there.
Upvotes: 0
Reputation: 7188
My solution would be to use brute force and split the string as needed, and update a HashMap
based on that. This probably is the simplest solution.
The other way is to use String Tokenizer, as Kyle suggested.
Third alternative is to replace beginning and ending markup so that it forms a valid XML and then parse that as XML. Yes, I am aware this particular is like shooting a fly with a cannon. But sometimes it may be needed and it is an option ;)
Upvotes: 1
Reputation: 24336
You need to do the following steps:
Upvotes: 0
Reputation: 185
Sounds like a school project so rather than solving the problem I'll just point you in the right direction: Check out the String Tokenizer Class
Upvotes: 3