[英]Java Regex - how to get all occurences inside the cbrackets in string?
我正在嘗試從字符串中獲取所有出現的事件(帶有搖籃的搖籃內部的文本)。
我試圖通過這種方式做到這一點:
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}
非常感謝您的任何建議
如果只需要使用大括號和其中的內容,則可以嘗試以下操作:
// | 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
的第一部分,該部分將與“不需要的”文本匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.