Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Khớp biểu thức chính quy (Regex Matching) trong JavaScript


Cho chuỗi đầu vào str và mẫu p, cài đặt khớp regex hỗ trợ '.' và '*'. Chức năng: '.' khớp bất kỳ ký tự đơn nào; '*' khớp 0 hoặc nhiều lần phần tử trước. Khớp phải bao phủ toàn bộ chuỗi đầu vào (không phải một phần).

Lưu ý - str có thể rỗng, chỉ chứa a-z. p có thể rỗng, chứa a-z, '.', '*'.

Ví dụ - str = 'aa', p = 'a' -> false (a không khớp toàn bộ 'aa').

Ví dụ

Code sau đây:

const regexMatching = (str, p) => { 
  const ZERO_OR_MORE_CHARS = '*'; 
  const ANY_CHAR = '.'; 
  const match = Array(str.length + 1).fill(null).map(() => Array(p.length + 1).fill(null)); 
  match[0][0] = true; 
  for (let col = 1; col <= p.length; col++) { 
    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++) match[row][0] = false; 
  for (let row = 1; row <= str.length; row++) { 
    for (let col = 1; col <= p.length; col++) { 
      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'));

Kết quả

Kết quả trên console:

true