巧用正则匹配解析返回数据

2018-12-19  本文已影响0人  嘻洋洋

1.应用技术

使用java.util.regex包下的Pattern和Matcher两个类

2.应用场景

//返回数据
window.QRLogin.code = 200; window.QRLogin.uuid = "XXXXXXX"
//解决方法
    Pattern UUID_PATTERN  = Pattern.compile("window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";");
    private String getUUID() {
        String response = getForObject(URL_UUID);
        Matcher matcher = UUID_PATTERN.matcher(response);
        if (matcher.find() && StateCode.SUCCESS.equals(matcher.group(1))) {
            return matcher.group(2);
        }
        return "";
    }
<error>
    <ret>0</ret>
    <message>OK</message>
    <skey>xxx</skey>
    <wxsid>xxx</wxsid>
    <wxuin>xxx</wxuin>
    <pass_ticket>xxx</pass_ticket>
    <isgrayscale>1</isgrayscale>
</error>

解决方法:

    public static String match(String reg, String text) {
        Pattern pattern = Pattern.compile(reg);
        Matcher m       = pattern.matcher(text);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }
        loginSession.setSKey(match("<skey>(\\S+)</skey>", body));
        loginSession.setWxSid(match("<wxsid>(\\S+)</wxsid>", body));
        loginSession.setWxUin(match("<wxuin>(\\S+)</wxuin>", body));
        loginSession.setPassTicket(match("<pass_ticket>(\\S+)</pass_ticket>", body));
上一篇下一篇

猜你喜欢

热点阅读