最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript -- get only the variable part of a regex match - Stack Overflow

programmeradmin0浏览0评论

given:

var regexp = new RegExp("<~~include(.*?)~~>", "g");

What's the easist way in javascript to assign a variable to whatever's matched by .*?

I can do this, but it's a little ugly:

myString.match(regexp).replace("<~~include", "").replace("~~>", "");

given:

var regexp = new RegExp("<~~include(.*?)~~>", "g");

What's the easist way in javascript to assign a variable to whatever's matched by .*?

I can do this, but it's a little ugly:

myString.match(regexp).replace("<~~include", "").replace("~~>", "");
Share Improve this question edited Aug 4, 2010 at 20:26 Matt Ball 360k102 gold badges653 silver badges720 bronze badges asked Aug 4, 2010 at 20:23 morgancodesmorgancodes 25.3k39 gold badges138 silver badges191 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 8

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:

var myVar = regexp.exec(myString)[1];

Should assign the value of the (.*?) capture group to myVar.

(Quotes from 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'.

Since .*? is the first (and only) remembered match, use $1 in your replacement string:

var foo = myString.replace(regexp, '$1');

Edit: As per your comment, you can also (perhaps with clearer intention) do this:

var foo = regexp.exec(myString)[1];

You can use lookahead for part of this regular expression. See here:

Regular expression for extracting a number

and/or here:

http://www.regular-expressions.info/lookaround.html

发布评论

评论列表(0)

  1. 暂无评论