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