search

Home  >  Q&A  >  body text

javascript - (?=exp) zero-width positive prediction lookahead assertion, how to use it, and why it doesn’t work

'<img abc 123 width="168" height="300"'.match(/(?=(width="))168/)

I expect to extract 123 located in width="123" from a string

Let me tell you what I can think of first. But this operation feels weird. Is there any cool way

Use replace and get it in the callback;

'<img abc 123 width="168" height="300"'.replace(/width="\d+"/,function(a){console.log(a)})

Or like @ars_qu

'<img abc 123 width="168" height="300"'.match(/width="\d+"/)[0].match(/\d+/)[0]
阿神阿神2752 days ago700

reply all(5)I'll reply

  • 高洛峰

    高洛峰2017-05-19 10:29:51

    js has poor support for assertions, just use matching groups directly:

    '<img abc 123 width="168" height="300"'.match(/width="(\d+)"/)[1]

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:29:51

    JS does not support reverse prefetch

    It currently supports forward lookup for zero-width assertions, that is, finding text that ends with a specified word (or other condition). --JS is currently supported;

    The requirement in your question is to find text preceded by the specified word (or other conditions). --JS is currently not supported.

    P.S.: Even if I support it, your writing is wrong! If you want to find the number after width, you need to use reverse lookup. The correct way to write it (in C# or PHP) is
    /(?<=width)d+/. Notice the extra less than sign. /(?<=width)d+/。 注意多了一个小于号。
    如果你想找width前面的数字,比如字符串是这样的"168width",这是用到的是正向预查,写法为 /d+(?=width)/If you want to find the number in front of width, for example, the string is like "168width", this is using

    forward lookup

    , which is written as /d+(?=width)/ .

    Standard Practice - Capturing Groups

    🎜Using regular capture is the best method in your scenario. 🎜
    '<img abc 123 width="168" height="300"'.match(/width="(\d+)/)[1];  //输出168

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-19 10:29:51

    用捕获,取RegExp.
    var str = '<img abc 123 width="168" height="300"/>';
    var reg = /.*(width\=\"(.*)\")\s.*/
    reg.test(str)
    console.log(reg.test(str), RegExp., RegExp.) 

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:29:51

    Can’t we just use width=".*?" and then match numbers

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:29:51

    js seems not to support some regular expressions, such as zero-width assertion....

    reply
    0
  • Cancelreply