Javascript 中等效于 Python 的 re.findall()

等效于使用 re.findall() 的此 Python 代码

js_equivalent_re_findall.py
import re

hashtag_regex = r"(\B#\w\w+)"
hits = re.findall(hashtag_regex, "This is a string #with #hashtags")
print(hits) # 打印 ['#with', '#hashtags']

在 Javascript 中是

js_findall_equivalent.js
const string = "This is a string #with #hashtags";
const re = /(\B#\w\w+)/g;
const hits = [];
// 迭代匹配
let match = null;
do {
    match = re.exec(string);
    if(match) {
        hits.push(match[0]);
    }
} while (match);

console.log(hits); // 打印 [ '#with', '#hashtags' ]

你需要将正则表达式分配给类似 re 的变量!如果你使用

js_findall_wrong.js
match = /(\B#\w\w+)/g.exec(string); // WRONG ! Don't do this !

你将创建一个无限循环,如果有的话,它总是生成字符串中的第一个匹配!


Check out similar posts by category: Javascript