JavaScript 中的正則表示式匹配
假設我們給定一個輸入字串 str 和一個模式 p,需要實現正則表示式匹配,並支援 . 和 *。
這些符號的作用應為:-
. --> 匹配任何單個字元。
* --> 匹配前一個元素 0 次或多次。
匹配應涵蓋整個輸入字串(不部分匹配)。
注意
str 可能為空,且僅包含小寫字母 a-z。
p 可能為空,且僅包含小寫字母 a-z 和字元 . 或 *。
舉例來說:
如果輸入為:
const str = 'aa'; const p = 'a';
則輸出應為 false,因為 a 無法匹配整個字串 aa。
示例
以下是程式碼:
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP