Javascript -- 只获取正则表达式匹配的可变部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3409520/
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 -- get only the variable part of a regex match
提问by morgancodes
given:
给出:
var regexp = new RegExp("<~~include(.*?)~~>", "g");
What's the easist way in javascript to assign a variable to whatever's matched by .*?
javascript 中将变量分配给.* 匹配的任何内容的最简单方法是什么?
I can do this, but it's a little ugly:
我可以做到这一点,但它有点难看:
myString.match(regexp).replace("<~~include", "").replace("~~>", "");
采纳答案by eldarerathis
Javascript should return an array object on a regex match, where the zero index of the array is the whole string that was matched and the following indexes are the capture groups. In your case something like:
Javascript 应该在正则表达式匹配时返回一个数组对象,其中数组的零索引是匹配的整个字符串,以下索引是捕获组。在你的情况下是这样的:
var myVar = regexp.exec(myString)[1];
var myVar = regexp.exec(myString)[1];
should assign the value of the (.*?)capture group to myVar.
应该将(.*?)捕获组的值分配给myVar.
回答by Matt Ball
(Quotes from MDC)
(来自MDC 的报价)
Including parentheses in a regular expression pattern causes the corresponding submatch to be remembered. For example,
/a(b)c/matches the characters'abc'and remembers'b'.
在正则表达式模式中包含括号会导致记住相应的子匹配。例如,
/a(b)c/匹配字符'abc'并记住'b'。
Since .*?is the first (and only) remembered match, use $1in your replacement string:
由于.*?是第一个(也是唯一一个)记住的匹配项,请$1在替换字符串中使用:
var foo = myString.replace(regexp, '');
Edit:As per your comment, you can also (perhaps with clearer intention) do this:
编辑:根据您的评论,您也可以(也许有更明确的意图)这样做:
var foo = regexp.exec(myString)[1];
回答by Skyler
You can use lookahead for part of this regular expression. See here:
您可以对这个正则表达式的一部分使用前瞻。看这里:
Regular expression for extracting a number
and/or here:
和/或在这里:

