简体   繁体   中英

Why my regex not working in this particular case

I want get out the number after "pw=" between these text

For example

"blablabla pw=0.5 alg=blablalbala"

would get me 0.5

The regex that I used was:

/.*pw=+(.*)\s+alg=.*/g

In the context of javascript, I would then use that regex in match function to get the number:

str.match(/.*pw=+(.*)\s+alg=.*/g)

But in regex101.com, the result of matching and highlight does not match at all(The result showed that the regex is correct while highlight part not)

You should remove the /g global modifier, and I suggest precising your value matching pattern to [\\d.]* .

The point is that when a global modifier is used with String#match , all captured group values are discarded.

Use a regex like

str.match(/\bpw=([\d.]*)\s+alg=/)
                 ^^^^^^        ^

Note that you do not need the .* at the start and end of the pattern, String#match does not require the full string match (unlike String#matches() in Java).

 var str = 'blablabla pw=0.5 alg=blablalbala'; var m = str.match(/\\bpw=([\\d.]*)\\s+alg=/); if (m) { console.log(m[1]); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM