简体   繁体   English

为什么我的正则表达式不适用于这种特殊情况

[英]Why my regex not working in this particular case

I want get out the number after "pw=" between these text 我希望在这些文本之间输出“pw =”之后的数字

For example 例如

"blablabla pw=0.5 alg=blablalbala"

would get me 0.5 会得到我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: 在javascript的上下文中,我将在匹配函数中使用该正则表达式来获取数字:

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) 但是在regex101.com中,匹配和高亮的结果根本不匹配(结果显示正则表达式是正确的而高亮部分没有)

You should remove the /g global modifier, and I suggest precising your value matching pattern to [\\d.]* . 你应该删除/g全局修饰符,我建议将你的值匹配模式精确到[\\d.]*

The point is that when a global modifier is used with String#match , all captured group values are discarded. 关键是当全局修饰符与String#match ,将丢弃所有捕获的组值。

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). 请注意,在模式的开头和结尾不需要.*String#match不需要完整的字符串匹配(与Java中的String#matches()不同)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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