简体   繁体   English

正则表达式:从字符到行尾的匹配,没有最后一个匹配组

[英]Regex: Match from character to end of line without the last match group

I want to extract the q param from some urls: 我想从一些网址中提取q参数:

.com/?gws_rd=ssl#q=test
.com/search?q=something+else&source=123

Here's a regex I came up with: q=(.*?)(&|$) . 这是我想出的一个正则表达式: q=(.*?)(&|$) When & terminates, the results are: &终止时,结果为:

["q=test", "test", "&"]

otherwise, when it hits the end of line: 否则,当它到达行尾时:

["q=test", "test", ""]

This works but doesn't seem right. 这有效,但似乎不正确。

Is there a way to not include the last match group at all, since I'm not interested in it? 因为我对此不感兴趣,有没有办法完全不包括最后一场比赛?

Turn the last group into a positive lookahead assertion. 将最后一组转变为正面的前瞻性断言。

(?=&|$) asserts that the match must be followed by a & or end of the line anchor $ (?=&|$)断言必须在匹配项后加上&或行锚$结尾

q=(.*?)(?=&|$)

DEMO 演示

> ".com/?gws_rd=ssl#q=test".match(/q=(.*?)(?=&|$)/)
[ 'q=test',
  'test',
  index: 17,
  input: '.com/?gws_rd=ssl#q=test' ]

To print only the chars inside the captured group. 仅打印捕获的组中的字符。

> var s = ".com/?gws_rd=ssl#q=test"
undefined
> console.log(/q=(.*?)(?=&|$)/.exec(s)[1]);
test

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

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