开发者

Retrieve regular expression results with in-depth info

Is there a way to retrieve regular expression object that contains the start position of the match, end position, total length etc.?

Or at least something like String.search(/pattern/), bu开发者_开发技巧t with more than one result.

Thanks in advance!


Exec is what you're looking for I'd say.

Edit:

for example (and using the code from the linked page):

var re = /d(b+)(d)/ig;  
var result = re.exec("cdbBdbsbz"); 
  • result.index is the start position
  • re.lastIndex is the end position
  • result[0].length is the total length


You could roll your own function based on exec, here is an example that builds a result object including index of all matches...

searchAll = function (text,pattern) {
  var result, output = [];
  while((result = pattern.exec(text)) != null) {
    output.push({
      result:result[0],
      index:result.index,
      lastIndex:pattern.lastIndex
    })
  }
  return output
}

var s = searchAll("JavaScript is more fun than Java!",/Java/g)

alert( JSON.stringify( s ) )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜