如何将重叠字符串与正则表达式匹配? [英] How can I match overlapping strings with regex?

查看:128
本文介绍了如何将重叠字符串与正则表达式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有字符串

"12345"

如果我 .match(/ \d {3} / g),我只获得一场比赛, 123。为什么我没有 [123,234,345]

If I .match(/\d{3}/g), I only get one match, "123". Why don't I get [ "123", "234", "345" ]?

推荐答案

单独使用正则表达式不能做到这一点,但你可以非常接近:

You can't do this with a regex alone, but you can get pretty close:

var pat = /(?=(\d{3}))\d/g;
var results = [];
var match;

while ( (match = pat.exec( '1234567' ) ) != null ) { 
  results.push( match[1] );
}

console.log(results);

换句话说,你捕捉前瞻中的所有三个数字,然后返回并以正常方式匹配一个字符,以提前匹配位置。你如何消费这个角色并不重要; 同样适用于 \d 。如果你真的喜欢冒险,你可以只使用前瞻,让JavaScript处理碰撞。

In other words, you capture all three digits inside the lookahead, then go back and match one character in the normal way just to advance the match position. It doesn't matter how you consume that character; . works just as well \d. And if you're really feeling adventurous, you can use just the lookahead and let JavaScript handle the bump-along.

此代码改编自此答案。我会将这个问题标记为该问题的副本,但OP接受了另一个较小的答案。

This code is adapted from this answer. I would have flagged this question as a duplicate of that one, but the OP accepted another, lesser answer.

这篇关于如何将重叠字符串与正则表达式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆