0

I am a beginner to regex.

I have below String:

fail:2,success:1,fetch:1

Output Map: Get Map which contains all key-values as below:

fail - 2 (key=fail, value=2)

success - 1

fetch - 1

I have tried using below solution:

public static void main(String arg[]) {            
String msg = "fail:1,success:1,policyfetch:1"; 
System.out.println(getKeyValuesFromMsg(msg));  
}                                                  

public static Map getKeyValuesFromMsg(String msg) {
  if (msg != null) {                             
    Map keyvalues = new HashMap();             
    Pattern p = Pattern.compile("(\\w+):(,+)");
    Matcher m = p.matcher(msg);                
    while (m.find()) {                         
        keyvalues.put(m.group(1), m.group(2)); 
    }                                          
    return keyvalues;                          
} else                                         
    return Collections.emptyMap();             
}                                               
5
  • And what's wrong with that solution? Commented Jun 21, 2018 at 10:16
  • not get any output Commented Jun 21, 2018 at 10:17
  • PS Map keyvalues = new HashMap(); - usage of raw types is rather bad practice (more reading: docs.oracle.com/javase/tutorial/java/generics/rawTypes.html) Commented Jun 21, 2018 at 10:18
  • Your regex is wrong, m.find() returns false and your loop is never executed. Commented Jun 21, 2018 at 10:19
  • @KamleshKanazariya Check my answer below. If the data is as simple as you have shown in your example. You can simply use the split function Commented Jun 21, 2018 at 10:20

3 Answers 3

2

You can use the split function, The following snippet should work fine

Map<String,String> map = new HashMap();
    String str = "fail:2,success:1,fetch:1";
    String[] keyValueParts = str.split(",");
    for(String s  : keyValueParts){
        String parts[] = s.split(":");
        map.put(parts[0],parts[1]);
    }

    System.out.println(map);
Sign up to request clarification or add additional context in comments.

Comments

0

i would have used below method for the same.

public static void main(String arg[]) {            
    String msg = "fail:1,success:1,policyfetch:1"; 
    System.out.println(getKeyValuesFromMsg(msg));  
    }

private static Map<Object, Object> getKeyValuesFromMsg(String msg) {
    Map<Object,Object> mapObj = new HashMap<Object,Object>();
    for (int i=0;i<msg.split(",").length;i++)
    mapObj.put(msg.split(",")[i].split(":")[0],msg.split(",")[i].split(":")[1]);
    return mapObj;
}

Comments

-1

my solution:

    public static Map<String, Integer> trans2Map(String source) {
    if (null == source) {
        return Collections.emptyMap();
    }
    Map<String, Integer> result = new HashMap<>();
    Arrays.stream(source.split(","))
            .filter(pair -> pair.split(":").length == 2)
            .forEach(pair -> {
                String key = pair.split(":")[0];
                Integer value;
                try {
                    value = Integer.parseInt(pair.split(":")[1]);
                } catch (Exception e) {
                    return;
                }
                result.put(key, value);
            });
    return result;
}

3 Comments

1. Why parsing to int? OP didn't ask about it. Furthemore, if value is not a number, the map will contain null for that key. 2. check for null != pair is redundant - String#split will never return array with nulls. 3. source.isEmpty() check is redundant - your check for "contains colon" in the stream's filter will handle it. 4. Why the trim()? OP didn't ask about it either - what if the spaces matter?
@ Jaroslaw Pawlak thanks for your comment: (1)、why parsing to int? this method just a demo,the map will contain null for that key(if value is not a number), really? (2)、you are right (3)、you are right (4)、 fix
1. no, sorry, my bad - I missed the return; in the catch :) By the way, when using stream API you should try to make as many small operations as possible, rather than having big blocks of code. That one in forEach can be converted into map, filter, map and collect. Also, modification of variables outside the stream is not a good practice (this result.put) and you should use collectors instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.