【问题标题】:How can I split a string multiple times in the same line?如何在同一行中多次拆分字符串?
【发布时间】:2020-08-09 20:36:02
【问题描述】:

我正在尝试通过将收到的响应正文拆分为字符串来操纵它,有没有办法可以在一行中获取 ProductName 而不是将其拆分为两行?

/script>dataLayer.push({'ecommerce': { 'detail': { 'products': [{ 'name': 'adidas Stan Smith cwhite / cwhite / dkblue', 'id': ' 017795', 'price': '1983', 'brand': 'adidas', 'category': 'Sneakers', 'sale': 'No sale', 'saleType': 'Sale: 0 %', 'variant' : ''}]}}});dataLayer.push({'ecomm_prodid': ['017795'],'ecomm_pagetype': 'product', 'ecomm_totalvalue': 2399.00});(function(w,d,s, l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'} );var f=d.getElementsByTagName(s)

编辑:这是我要拆分的 html 中的块,我正在尝试使用一行代码获取“adidas Stan Smith cwhite / cwhite / dkblue”


import (
    "io/ioutil"
    "log"
    "net/http"
    "strings"
)

func main() {
    for {
        log.Println("Sending..")
        resp, _ := http.Get("https://www.queens.global/59789/adidas-stan-smith/")

        defer resp.Body.Close()

        body, _ := ioutil.ReadAll(resp.Body)

        product := strings.Split(string(body), "name': '")[1]
        productName := strings.Split(product, "', 'id':")[0]
        log.Println(productName)
        break
    }
}

【问题讨论】:

  • 我们不知道您的字符串是什么样的。但不是。相反,请尝试使用正则表达式。
  • 抱歉,添加了我要从中拆分数据的块
  • 它是用 HTML 封装的 JSON,因此理想情况下,您应该使用 HTML 解析器提取 JSON,然后解析 JSON。没有拆分和正则表达式。
  • 另外,为什么是“一行代码”?
  • 谢谢,我可能会为这些数据执行此操作,但我还需要此页面上的一些其他信息,这些信息需要我拆分响应正文。只是我的一个不好的例子来展示这个 json 例子(很抱歉)。

标签: string http go data-manipulation


【解决方案1】:
{"ecommerce": { "detail": { "products": [{ "name": "adidas Stan Smith cwhite / cwhite / dkblue", "id": "017795", "price": "1983", "brand": "adidas", "category": "Sneakers", "sale": "No sale", "saleType": "Sale: 0 %", "variant": ""}]}}}

输出(字符串)中的这部分是 JSON。

获取所有内容的最佳方法是将相同的内容解析为 JSON,然后从同一个变量中获取结果。

你可以使用 new GSON().toJSON() 来做同样的事情。(或任何 JSON 解析器)

【讨论】:

    猜你喜欢
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多