无法解析java

时间:2017-08-13 06:17:25

标签: java user-agent

我收到以下用户代理字符串

["Mozilla/5.0","(Macintosh;","Intel","Mac","OS","X","10.8;","rv:31.0)","Gecko/20100101","Firefox/31.0"]

我正在尝试将其解析为字符串并将其转换为字符串数组,但我无法将其作为字符串读取。是否有更好的方法来读取用方括号括起来的用户代理数据

public class AgentParse{

     public static void main(String []args){
        String a="""["Mozilla/5.0","(Macintosh;","Intel","Mac","OS","X","10.8;","rv:31.0)","Gecko/20100101","Firefox/31.0"]""";
        String st=a.replace('[', ' ').replace(']', ' ').replace('(', ' ').replace(')', ' ');
        String[] arr=st.split(",");
        System.out.println(arr[0]);

        }

我有一个这样的字符串列表,我不能复制粘贴每个字符串并转义字符。我在java中寻找一个可以保存上述数据的数据类型

2 个答案:

答案 0 :(得分:0)

从您现有的代码中,您似乎在寻找Mozilla/5.0作为输出。所以,首先你需要逃避所有双引号

String str = "[\"Mozilla/5.0\",\"(Macintosh;\",\"Intel\",\"Mac\",\"OS\",\"X\",\"10.8;\",\"rv:31.0)\",\"Gecko/20100101\",\"Firefox/31.0\"]";
System.out.println(str.split(",")[0].replace("[",""));

将输出

"Mozilla/5.0"

答案 1 :(得分:0)

如果要解析所有字符串。

String a = "[\"Mozilla/5.0\",\"(\"Macintosh;\",\"Intel\",\"Mac\",\"OS\",\"X\",\"10.8;\",\"rv:31.0\")\",\"Gecko/20100101\",\"Firefox/31.0\"]";
String[] newArray = a.split(",");
    for (String s : newArray) {
        System.out.println(s);
    }
}

输出

["Mozilla/5.0"
"("Macintosh;"
"Intel"
"Mac"
"OS"
"X"
"10.8;"
"rv:31.0")"
"Gecko/20100101"
"Firefox/31.0"]