我正在尝试从字符串中获取所有出现的内容(带有cbrackets的cbrackets中的文本)。
我试着这样做:
String DATA = "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=\"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=\"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=\"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" +
"}";
String re1=".*?"; // Non-greedy match on filler
String re2="(\\{.*?\\})"; // Curly Braces 1
List<String> allMatches = new ArrayList<String>();
Pattern p = Pattern.compile(re1 + re2, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(DATA);
while (m.find()) {
allMatches.add(m.group());
}
for(int i = 0; i < allMatches.size(); i++) {
Logger.d(allMatches.get(i).toString());
}
但首先发现的结果包含不需要的字符:
使用“network =”字符串返回下次发现的出现次数。
如何才能提高我的正则表达式才能只显示格式?:
{whole content in cbracket}
非常感谢任何建议
答案 0 :(得分:1)
如果你只需要获得大括号和内部的内容,你可以试试这个:
// | escaped opening bracket
// | | any character, 0+ times
// | | | closing bracket
// | | | | dot will also match new lines
Pattern p = Pattern.compile("\\{.*?}", Pattern.DOTALL);
Matcher m = p.matcher(DATA);
while (m.find()) {
System.out.println(m.group());
}
根据您的输入,它将打印:
{
ssid="test1"
psk="154695"
key_mgmt=WPA-PSK
sim_slot="-1"
imsi="none"
priority=1
}
{
ssid="SSID2"
psk="test123456"
key_mgmt=WPA-PSK
sim_slot="-1"
imsi="none"
priority=19
}
备注强>
Pattern
的第一部分,这部分符合&#34;不需要的&#34;文本。