JavaScript-Äquivalent zu Pythons re.findall()

English Deutsch

Das Äquivalent zu diesem Python-Code, der re.findall() verwendet,

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) # gibt ['#with', '#hashtags'] aus

in JavaScript ist

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

console.log(hits); // Gibt [ '#with', '#hashtags' ] aus

Sie müssen Ihren regulären Ausdruck einer Variablen wie re zuweisen! Wenn Sie

js_findall_wrong.js
match = /(\B#\w\w+)/g.exec(string); // FALSCH! Tun Sie das nicht!

erzeugen Sie eine Endlosschleife, die immer wieder den ersten Treffer im String erzeugt, falls vorhanden!


Check out similar posts by category: Javascript