javascript - (?=exp) zero-width positive prediction lookahead assertion, how to use it, and why it doesn't work
阿神
阿神 2017-05-19 10:27:51
0
5
677

'<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]
阿神
阿神

闭关修行中......

reply all(5)
小葫芦

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

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

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
大家讲道理
用捕获,取RegExp.
var str = '<img abc 123 width="168" height="300"/>';
var reg = /.*(width\=\"(.*)\")\s.*/
reg.test(str)
console.log(reg.test(str), RegExp., RegExp.) 
我想大声告诉你

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

小葫芦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!