From b18721a4e545b838f6190d1068cd9ec41e126c87 Mon Sep 17 00:00:00 2001 From: Gabe Yuan Date: Fri, 18 Aug 2023 13:16:17 +0800 Subject: [PATCH] wildcard is supported --- src/config/i18n.js | 4 ++-- src/libs/index.js | 4 ++-- src/libs/utils.js | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/config/i18n.js b/src/config/i18n.js index 56a24e0..368e52d 100644 --- a/src/config/i18n.js +++ b/src/config/i18n.js @@ -153,8 +153,8 @@ export const I18N = { en: `URL pattern`, }, pattern_helper: { - zh: `多个URL支持英文逗号“,”分隔`, - en: `Multiple URLs can be separated by English commas ","`, + zh: `1、支持星号(*)通配符。2、多个URL支持英文逗号“,”分隔。`, + en: `1. The asterisk (*) wildcard is supported. 2. Multiple URLs can be separated by English commas ",".`, }, selector_helper: { zh: `1、遵循CSS选择器规则。2、留空表示采用全局设置。`, diff --git a/src/libs/index.js b/src/libs/index.js index dd84274..92b4c97 100644 --- a/src/libs/index.js +++ b/src/libs/index.js @@ -9,6 +9,7 @@ import { BUILTIN_RULES, } from "../config"; import { browser } from "./browser"; +import { isMatch } from "./utils"; /** * 获取节点列表并转为数组 @@ -48,7 +49,6 @@ export const setFab = async (obj) => await storage.setObj(STOKEY_FAB, obj); /** * 根据href匹配规则 - * TODO: 支持通配符(*)匹配 * @param {*} rules * @param {string} href * @returns @@ -59,7 +59,7 @@ export const matchRule = (rules, href, { injectRules }) => { } const rule = rules.find((rule) => - rule.pattern.split(",").some((p) => href.includes(p.trim())) + rule.pattern.split(",").some((p) => isMatch(href, p.trim())) ); const globalRule = rules.find((rule) => diff --git a/src/libs/utils.js b/src/libs/utils.js index c0fb589..93264b7 100644 --- a/src/libs/utils.js +++ b/src/libs/utils.js @@ -51,3 +51,40 @@ export const debounce = (func, delay = 200) => { }, delay); }; }; + +/** + * 字符串通配符(*)匹配 + * @param {*} s + * @param {*} p + * @returns + */ +export const isMatch = (s, p) => { + if (s.length === 0 || p.length === 0) { + return false; + } + + p = `*${p}*`; + + let [sIndex, pIndex] = [0, 0]; + let [sRecord, pRecord] = [-1, -1]; + while (sIndex < s.length && pRecord < p.length) { + if (p[pIndex] === "*") { + pIndex++; + [sRecord, pRecord] = [sIndex, pIndex]; + } else if (s[sIndex] === p[pIndex]) { + sIndex++; + pIndex++; + } else if (sRecord + 1 < s.length) { + sRecord++; + [sIndex, pIndex] = [sRecord, pRecord]; + } else { + return false; + } + } + + if (p.length === pIndex) { + return true; + } + + return p.slice(pIndex).replaceAll("*", "") === ""; +};