正则表达式从Java请求中提取变量

时间:2017-11-25 15:40:46

标签: java regex notepad++ notepad

所以我有一个工具可以扫描API以进行更改。如果他发现了变化,他会得到一个像:

这样的字符串
word=\don\u2019t\ item-id=\"1086\">\n        <span class=\

我想从item-id中提取数字,但响应中有多个数字。

有可能这样做吗? (我也不知道数字是4位还是1-2位)

所以正则表达式应该搜索类似&#34; NUMBERS \&#34;然后打印出来。 (对于Java)

2 个答案:

答案 0 :(得分:2)

基于your comment,您似乎正在接收JSON结构

{
    ...
    "data":{
        "html":".. <a .. data-sku=\"XXX\"> ..",
        ...
    }
    ...
}

您对data-sku属性的价值感兴趣。

在这种情况下,解析JSON并遍历它以获得HTML结构。您可以使用org.json.JSONObject(或其他解析器,选择您喜欢的一个)

String response = "{\"success\":1,\"data\":{\"html\":\"<div class=\\\"inner\\\">\\n      <span class=\\\"title js-title-eligible\\\">Upgrade available<\\/span>\\n    <span class=\\\"title js-title-warning\\\"><strong>WARNING :<\\/strong> You don\\u2019t own a <span class=\\\"js-from-ship\\\"><\\/span><\\/span>\\n        <p class=\\\"explain js-title-eligible\\\">Buy this upgrade and it will be applicable to your <span class=\\\"js-from-ship\\\"><\\/span> from the My Hangar section.<\\/p>\\n    <p class=\\\"explain js-title-warning\\\">You can buy this upgrade but it will only be applicable on a <span class=\\\"js-from-ship\\\"><\\/span>.<\\/p>\\n\\n    <div class=\\\"price\\\"><strong class=\\\"final-price\\\">\\u20ac5<span class='super'>.41 <span class='currency'>EUR<\\/span><\\/span><\\/strong><div class=\\\"taxes js-taxes\\\">\\n  <div class=\\\"taxes-details trans-02s\\\">\\n    <div class=\\\"arrow\\\"><\\/div>\\n    Tax Included: <br \\/>\\n    <ul>\\n        <li>VAT 19%<\\/li>\\n        <\\/ul>\\n  <\\/div>\\n<\\/div><\\/div>\\n\\n\\n    <div>\\n      <a href=\\\"\\/pledge\\/Upgrades\\/Mustang-Alpha-To-Aurora-LN-Upgrade\\\" class=\\\"add-to-cart holosmallbtn trans-03s js-add-to-cart-ship ty-js-add-to-cart\\\" data-sku=\\\"1086\\\">\\n        <span class=\\\"holosmallbtn-top abs-overlay trans-02s\\\">BUY NOW<\\/span>\\n        <span class=\\\"holosmallbtn-bottom abs-overlay trans-02s\\\"><\\/span>\\n      <\\/a>\\n      <a href=\\\"\\/pledge\\/Upgrades\\/Mustang-Alpha-To-Aurora-LN-Upgrade\\\" class=\\\"more-details\\\">View more details<\\/a>\\n    <\\/div>\\n    \\n    <p class=\\\"explain info\\\">\\n      Upgrades that you buy can be found in your <a href=\\\"\\/account\\/pledges\\\">Hangar section<\\/a>.<br \\/>\\n      Click \\\"Apply Upgrade\\\" inside the Upgrade Pledge to pick where you want to apply it.\\n    <\\/p>\\n  <\\/div>\\n\\n\\n\\n\"},\"code\":\"OK\",\"msg\":\"OK\"}";

JSONObject jsonObject = new JSONObject(response);
String html = jsonObject.getJSONObject("data") //pick data:{...} object
                        .getString("html");    //from that object get value of html:"..."

现在你有html你可以用HTML解析器解析它(我正在使用jsoup)

Document doc = Jsoup.parse(html);
String dataSku = doc.select("a[data-sku]") //get "a" element with "data-sku" attribute
                    .attr("data-sku");     //value of that attribute

输出:1086

答案 1 :(得分:0)

connect