Reputation: 1259
I am a beginner to regex.
I have below String:
Hi Welcome to my site. #binid:BIN-4 #lat:23.025243 #long:72.5980293 #nottype:assign
Output Map : Get Map which contains all key-values as below:
bindid - BIN-4 (key=bindid, value=BIN-4)
lat - 23.025243
long - 72.5980293
nottype - assign
Upvotes: 1
Views: 63
Reputation: 1132
you can extend your regex in next way:
1) initial split to get pairs (as you do it now)
2) for every pair perform another split by :
which will give you first element as key and second element as value
code snippet:
public class Main {
public static void main(String[] args) {
Map<String, String> result = new HashMap<>();
String input = "Hi Welcome to my site. #binid:BIN-4 #lat:23.025243 #long:72.5980293 #nottype:assign";
String systemData = input.replace("Hi Welcome to my site. ", "");
Arrays.asList(systemData.split("#")).forEach(pair -> {
if (!pair.isEmpty()) {
String[] split = pair.split(":");
result.put(split[0], split[1]);
}
});
result.entrySet().forEach( pair -> System.out.println("key: " + pair.getKey() + " value: " + pair.getValue()));
}
}
Result:
key: binid value: BIN-4
key: nottype value: assign
key: lat value: 23.025243
key: long value: 72.5980293
Upvotes: 0
Reputation: 2751
You can try below approach for this:
String s = "Hi Welcome to my site. #binid:BIN-4 #lat:23.025243 #long:72.5980293 #nottype:assign";
String startsWithHash = s.substring(s.indexOf('#')+1);
String arr[] = startsWithHash.split("#");
Map<String, String> map = new HashMap<>();
Arrays.stream(arr).forEach(element -> map.put(element.split(":")[0], element.split(":")[1]));
System.out.println(map.toString());
O/P:
{binid=BIN-4 , nottype=assign, lat=23.025243 , long=72.5980293 }
Upvotes: 1
Reputation: 626738
You may find #
, capture 1+ word chars after in the first group, match :
, and then capture 1+ non-whitespace chars into the second group:
String str = "Hi Welcome to my site. #binid:BIN-4 #lat:23.025243 #long:72.5980293 #nottype:assign";
Map<String, String> res = new HashMap<String, String>();
Pattern p = Pattern.compile("#(\\w+):(\\S+)");
Matcher m = p.matcher(str);
while(m.find()) {
res.put(m.group(1),m.group(2));
System.out.println(m.group(1) + " - " + m.group(2)); // Demo output
}
See the Java demo.
Output:
binid - BIN-4
lat - 23.025243
long - 72.5980293
nottype - assign
Pattern details:
#
- a #
symbol (\\w+)
- Capturing group 1: one or more word chars:
- a colon(\\S+)
- Capturing group 2: one or more non-whitespace chars Upvotes: 1