【问题标题】:Regex: how to get the "width" and "height" value from this string which is right after "bitwise" value?正则表达式:如何从此字符串中获取“按位”值之后的“宽度”和“高度”值?
【发布时间】:2020-05-17 01:57:45
【问题描述】:

假设我有这个字符串:

,"mimeType":"video/mp4;+codecs=\"avc1.42001E,+mp4a.40.2\"","bitrate":353051,"width":640,"height":320,"lastModified":"1543659519195688","contentLength":"24469560","quality":"medium","fps":24,"qualityLabel":"360p","projectionType":"RECTANGULAR","averageBitrate":35300;codecs=\"avc1.64001F,+mp4a.40.2\"","bitrate":987359,"width":1280,"height":640,"lastModified":"1543660211977003","quality":"hd720","fps":24,"qualityLabel":"720p","projectionType":"RECTANGULAR

我需要提取紧跟在"bitrate" 字符串之后的所有宽度和高度对值。

请注意,字符串有两倍的宽度和高度。我需要两对:

"bitrate":353051,"width":640,"height":320

"bitrate":987359,"width":1280,"height":640

请注意,我只需要获取紧随其后的是 "bitrate" 值的那些。如果之前没有 "bitrate" 值,那么我不想要它。

所以答案应该是:

640,320
1280,640

我已经把字符串粘贴到这里了:

https://regex101.com/r/VXAyvV/2

【问题讨论】:

标签: regex regex-greedy


【解决方案1】:

您可以使用这个正则表达式,它只会匹配紧跟bitrate 值的width 和height:

"bitrate":\d+,"width":(\d+),"height":(\d+)

宽度和高度将分别在第 1 组和第 2 组中捕获。

Demo on regex101

【讨论】:

    【解决方案2】:

    您可以使用以下正则表达式。

    "bitrate":(?=.*?"width":(?<width>\d+))(?=.*?"height":(?<height>\d+))
    

    Demo

    我使用 PCRE (PHP) 正则表达式引擎对其进行了测试,但它应该适用于所有支持正预测的引擎,即大多数正则表达式引擎。

    我使用了命名的捕获组,但这不是必需的,因为总是首先捕获宽度(在匹配"bitrate" 之后),即使它跟随字符串中的高度。在"bitrate" 和"width" 和"bitrate" 和"height" 之间可以有中间字段。

    考虑以下字符串。

    "qual":"360p","bitrate":987359,"wt":90,"width":1280,"fps":24,"height":640,"last":"154"

    当与正则表达式匹配时,名为width 的捕获组将持有"1280",而height 的捕获组将持有"640"。

    正则表达式引擎执行以下操作。

    "bitrate":       match '"bitrate":'
    (?=              begin a positive lookahead
      .*?            lazily match 0+ chars other than newlines
      "width":       match '"width":'
      (?<width>\d+)  match 1+ digits and save to capture group 'width'
    )                end positive lookahead
    (?=              begin a positive lookahead
      .*?            lazily match 0+ chars other than newlines
      "height":      match '"height":'
      (?<height>\d+) match 1+ digits and save to capture group 'height'
    )                end positive lookahead
    

    【讨论】:

      猜你喜欢
      • 2012-05-30
      • 1970-01-01
      • 2014-11-05
      • 2011-09-14
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      相关资源
      最近更新 更多