What Regex Use To Get Network Object From Wpa_supplicant.conf?
I have file with the following structure: ctrl_interface=/data/misc/wifi/sockets driver_param=use_p2p_group_interface=1 update_config=1 device_name=P580_ROW manufacturer=LENOVO mod
Solution 1:
If you do not know the names of attributes and their count, you can make use of a regex based on \G
operator:
String str ="<<YOUR_STRING>>";
Pattern ptrn =Pattern.compile("(?<new>network=\\{|(?!^)\\G)\\s*(?<key>\\w+)=\"?(?<value>[^\"\n]+)\"?");
Matcher matcher = ptrn.matcher(str);
int count =1;
while (matcher.find()) {
if (matcher.group("new") != null && matcher.group("new").length() >0) {
System.out.println("New Network: "+ count);
count +=1;
}
System.out.println(matcher.group("key") +":\""+ matcher.group("value").trim() +"\"");
}
See IDEONE demo
The regex - (?<new>network=\{|(?!^)\G)\s*(?<key>\w+)="?(?<value>[^"\n]+)"?
- matches:
(?<new>network=\{|(?!^)\G)
-network={
or the end of the previous successful match (Group "new")\s*
- optional whitespace(?<key>\w+)
- 1 or more alphanumeric symbols (Group "key")="?
- literal=
and an optional"
(?<value>[^"\n]+)
- 1 or more characters other than"
and a newline (Group "value")"?
- an optional"
Solution 2:
Here is a working example. Try it.
publicclassTest {
privatestaticfinalStringREGEXP="network=\\{\\n\\s*ssid=\"(?<ssid>.*)\"\\n\\s*psk=\"(?<psk>.*)\"\\n\\s*key_mgmt=(?<keymgmt>.*)\\n\\s*sim_slot=\"(?<simslot>.*)\"\\n\\s*imsi=\"(?<imsi>.*)\"\\n\\s*priority=(?<priority>.*)\\n}";
privatestaticfinalStringDATA="ctrl_interface=/data/misc/wifi/sockets\n"+"driver_param=use_p2p_group_interface=1\n"+"update_config=1\n"+"device_name=P580_ROW\n"+"manufacturer=LENOVO\n"+"model_name=Lenovo \n"+"model_number=Lenov\n"+"serial_number=hjhjh7\n"+"device_type=10-0050F204-5\n"+"os_version=01020300\n"+"config_methods=physical_display virtual_push_button\n"+"p2p_no_group_iface=1\n"+"\n"+"network={\n"+" ssid=\"test1\"\n"+" psk=\"154695\"\n"+" key_mgmt=WPA-PSK\n"+" sim_slot=\"-1\"\n"+" imsi=\"none\"\n"+" priority=1\n"+"}\n"+"\n"+"network={\n"+" ssid=\"SSID2\"\n"+" psk=\"test123456\"\n"+" key_mgmt=WPA-PSK\n"+" sim_slot=\"-1\"\n"+" imsi=\"none\"\n"+" priority=19\n"+"}";
publicstatic void main(String[] args){
finalPattern pattern =Pattern.compile(REGEXP);
finalMatcher matcher = pattern.matcher(DATA);
while(matcher.find()){
System.out.println("New network");
System.out.println("-----------");
System.out.println("SSID: "+matcher.group("ssid"));
System.out.println("PSK: "+matcher.group("psk"));
System.out.println("KEY MGMT: "+matcher.group("keymgmt"));
System.out.println("SIM SLOT: "+matcher.group("simslot"));
System.out.println("IMSI: "+matcher.group("imsi"));
System.out.println("PRIORITY: "+matcher.group("priority"));
}
}
}
I am not efficient in RegExp. I think this method is dirty and there'd be better solutions than this.(WorkSpace: https://regex101.com/r/nA8fD1/1)
Post a Comment for "What Regex Use To Get Network Object From Wpa_supplicant.conf?"