JavaScriptでの正規表現マッチング
入力文字列strとパターンpが与えられたとすると、をサポートする正規表現マッチングを実装する必要があります。および*。
これらの記号の機能は-
である必要があります-
。 ->任意の1文字に一致します。
-
*->先行する要素の0個以上に一致します。
マッチングは、入力文字列全体(部分的ではない)をカバーする必要があります。
注
-
strは空で、小文字のa〜zのみが含まれている可能性があります。
-
pは空である可能性があり、小文字のa〜zとのような文字のみが含まれます。または*。
例-
入力が-
の場合const str = 'aa'; const p = 'a';
その場合、aは文字列aa全体と一致しないため、出力はfalseになります。
例
以下はコードです-
const regexMatching = (str, p) => {
const ZERO_OR_MORE_CHARS = '*';
const ANY_CHAR = '.';
const match = Array(str.length + 1).fill(null).map(() => {
return Array(p.length + 1).fill(null);
});
match[0][0] = true;
for (let col = 1; col <= p.length; col += 1) {
const patternIndex = col - 1;
if (p[patternIndex] === ZERO_OR_MORE_CHARS) {
match[0][col] = match[0][col - 2];
} else {
match[0][col] = false;
}
}
for (let row = 1; row <= str.length; row += 1) {
match[row][0] = false;
}
for (let row = 1; row <= str.length; row += 1) {
for (let col = 1; col <= p.length; col += 1) {
const stringIndex = row - 1;
const patternIndex = col - 1;
if (p[patternIndex] === ZERO_OR_MORE_CHARS) {
if (match[row][col - 2] === true) {
match[row][col] = true;
} else if (
(
p[patternIndex - 1] === str[stringIndex]
|| p[patternIndex - 1] === ANY_CHAR
)
&& match[row - 1][col] === true
) {
match[row][col] = true;
} else {
match[row][col] = false;
}
} else if (
p[patternIndex] === str[stringIndex]
|| p[patternIndex] === ANY_CHAR
) {
match[row][col] = match[row - 1][col - 1];
} else {
match[row][col] = false;
}
}
}
return match[str.length][p.length];
};
console.log(regexMatching('aab', 'c*a*b')); 出力
以下はコンソールでの出力です-
true
-
JavaScriptでの名前付き関数式
以下は、JavaScriptで名前付き関数式を実装するためのコードです。 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> &nb
-
JavaScriptのyield*式/キーワード。
yield *式は、別のジェネレーターまたは反復可能なオブジェクトを参照するために使用されます。 以下は、JavaScriptでyield*式/キーワードを実装するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /&g