【问题标题】:sed JSON regular expressionsed JSON 正则表达式
【发布时间】:2017-07-28 13:13:15
【问题描述】:

为这种愚蠢的问题道歉,但这是我第一次使用curl 命令,现在我从某个地方得到这个命令来提取以下字符串

{"success":true,"results":1,"total":1,"more":false,"offset":0,"hits":[{"path":"/home/users/ Vq7DPVRHzGVK--OTJsHs","excerpt":"","name":"Vq7DPVRHzGVK--OTJsHs","title":"Vq7DPVRHzGVK--OTJsHs","lastModified":"2017-03-03 16:45:46","创建":"2017-03-03 16:45:46"}]}

我使用以下脚本将curl 输出通过管道传输到sed

sed -e 's/^.*"path":"\([^"]*\)".*$/\1/

结果:

/home/users/Vq7DPVRHzGVK--OTJsHs

谁能解释一下这里的正则表达式是如何工作的?以及如何仅获得 Vq7DPVRHzGVK--OTJsHs 的结果而不包括 /home/user 路径?

【问题讨论】:

    标签: json regex sed


    【解决方案1】:

    解释:

    s/   ^.*"path":"\([^"]*\)".*$   /  \1   /
          ----------^------------     ---^---
                 Pattern         Replacement string 
    

    正则表达式的工作原理:

    ^.*         # Match beginning of input string & anything else
    "path":"    # Up to literal string `"path":"`
    \([^"]*\)   # Then match slash and match + group anything up to a double quote `"`
    ".*$        # Match double quote and the rest of input string
    

    通过替换字符串\1,您将整个匹配部分替换为第一个捕获组,该捕获组是路径值双引号之间的所有内容,除了开头的斜杠。

    您想要的是将捕获组从捕获整个部分更改为最后一部分:

    s/^.*"path":"[^"]*\/\([^"]*\)".*$/\1/
    

    【讨论】:

    • @SLePort 除了对 revo 的赞赏和赞美之外,我做得很好,对吧?
    • @DEN 抱歉,评论太快了。我没看出你是个有经验的用户……
    【解决方案2】:

    Regex demo

    正则表达式:.*"path\":"\K[\/\w]+(?=\/)\/\K[^"]+

    【讨论】:

    • 我在返回 sed: -e expression #1, char 39: unterminated `s' command 时得到了这个错误
    • SED 不支持 PCRE。
    • 欢迎@DEN :)
    猜你喜欢
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 2010-09-19
    • 2018-08-22
    相关资源
    最近更新 更多