简体   繁体   English

正则表达式匹配的最后一个字符

[英]Last Character of regex match

I am trying to use a regex to detect a pattern in the current page query string. 我正在尝试使用正则表达式来检测当前页面查询字符串中的模式。

For this reason I have the following regex: 因此,我有以下正则表达式:

var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)", "i");

I am testing it against this input: 我正在针对此输入进行测试:

http://127.0.0.1:33822/?year=2015&country=Portugal&format=psd

And it works just fine finding the pattern. 而且找到模式也很好。

What I am really trying to get is the last character index relative to the whole URL. 我真正想要得到的是相对于整个URL的最后一个字符索引。

So for example if I want the index o the last 'd' character: 因此,例如,如果我想要索引o的最后一个'd'字符:

http://127.0.0.1:33822/?year=2015&country=Portugal&format=ps**d**

In this specific case I would want 60. 在这种情况下,我想要60。

Thanks in advance 提前致谢

You can use match.index for that. 您可以match.index使用match.index It will give you where the match exists in the original string. 它将为您提供原始字符串中存在匹配项的位置。 Then you can use the matche[0].length to find the last character in the match 然后,您可以使用matche[0].length查找匹配中的最后一个字符

 key='format'
 re = new RegExp("([?|&])" + key + "=.*?(&|#|$)", "i");
 url='http://127.0.0.1:33822/?year=2015&country=Portugal&format=psd'

match=url.match(re)

console.log(match.index + match[0].length-1) // 60

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

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