Javascript Regexp - 匹配特定短语后的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4571531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Regexp - Match Characters after a certain phrase
提问by bryan sammon
I was wondering how to use a regexp to match a phrase that comes after a certain match. Like:
我想知道如何使用正则表达式来匹配某个匹配后出现的短语。喜欢:
var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var match = /phrase=.*/;
That will match from the phrase=
to the end of the string, but is it possible to get everything after the phrase=
without having to modify a string?
这将从phrase=
字符串的末尾匹配到字符串的末尾,但是是否可以在phrase=
无需修改字符串的情况下获取所有内容?
回答by DVK
You use capture groups(denoted by parenthesis).
您使用捕获组(用括号表示)。
When you execute the regex via match or exec function, the return an array consisting of the substrings captured by capture groups. You can then access what got captured via that array. E.g.:
当您通过 match 或 exec 函数执行正则表达式时,返回一个由捕获组捕获的子字符串组成的数组。然后,您可以访问通过该数组捕获的内容。例如:
var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var myRegexp = /phrase=(.*)/;
var match = myRegexp.exec(phrase);
alert(match[1]);
or
或者
var arr = phrase.match(/phrase=(.*)/);
if (arr != null) { // Did it match?
alert(arr[1]);
}
回答by thejh
phrase.match(/phrase=(.*)/)[1]
returns
返回
"thisiswhatIwantmatched"
The brackets specify a so-called capture group. Contents of capture groups get put into the resulting array, starting from 1 (0 is the whole match).
括号指定了所谓的捕获组。捕获组的内容被放入结果数组中,从 1 开始(0 是整个匹配项)。
回答by Bao Mai
Let try this, I hope it work
让我们试试这个,我希望它有效
var p = /\b([\w|\W]+)+(\=)([\w|\W]+)+\b/;
console.log(p.test('case1 or AA=AA ilkjoi'));
console.log(p.test('case2 or AA=AB'));
console.log(p.test('case3 or 12=14'));
回答by AmerllicA
It is not so hard, Just assume your context is :
这并不难,假设您的上下文是:
const context = https://medicoads.net/pa/GIx89GdmkABJEAAA+AAAA
And we wanna have the pattern after pa/
, so use this code:
我们想要在 之后pa/
使用模式,所以使用以下代码:
const pattern = context.match(/pa\/(.*)/)[1];
The first item include pa/
, but for the grouping second item is without pa/
, you can use each what you want.
第一项包括pa/
,但对于分组,第二项没有pa/
,您可以使用您想要的每一项。
回答by AlexNikonov
If you want to get value after the regex excluding the test phrase, use this:
/(?:phrase=)(.*)/
如果您想在不包括测试短语的正则表达式之后获取值,请使用以下命令:
/(?:phrase=)(.*)/
the result will be
结果将是
0: "phrase=thisiswhatIwantmatched" //full match
1: "thisiswhatIwantmatched" //matching group