This commit is contained in:
Horis
2025-04-07 17:11:16 +08:00
parent f21adfe93f
commit 785703a6c6
@@ -64,6 +64,7 @@ class AnalyzeRule(
private var analyzeByJSonPath: AnalyzeByJSonPath? = null private var analyzeByJSonPath: AnalyzeByJSonPath? = null
private val stringRuleCache = hashMapOf<String, List<SourceRule>>() private val stringRuleCache = hashMapOf<String, List<SourceRule>>()
private val regexCache = hashMapOf<String, Regex?>()
private var coroutineContext: CoroutineContext = EmptyCoroutineContext private var coroutineContext: CoroutineContext = EmptyCoroutineContext
@@ -413,29 +414,48 @@ class AnalyzeRule(
*/ */
private fun replaceRegex(result: String, rule: SourceRule): String { private fun replaceRegex(result: String, rule: SourceRule): String {
if (rule.replaceRegex.isEmpty()) return result if (rule.replaceRegex.isEmpty()) return result
var vResult = result val replaceRegex = rule.replaceRegex
vResult = if (rule.replaceFirst) { val replacement = rule.replacement
val regex = compileRegexCache(replaceRegex)
if (rule.replaceFirst) {
/* ##match##replace### 获取第一个匹配到的结果并进行替换 */ /* ##match##replace### 获取第一个匹配到的结果并进行替换 */
kotlin.runCatching { if (regex != null) kotlin.runCatching {
val pattern = Pattern.compile(rule.replaceRegex) val pattern = regex.toPattern()
val matcher = pattern.matcher(vResult) val matcher = pattern.matcher(result)
if (matcher.find()) { return if (matcher.find()) {
matcher.group(0)!!.replaceFirst(rule.replaceRegex.toRegex(), rule.replacement) matcher.group(0)!!.replaceFirst(regex, replacement)
} else { } else {
"" ""
} }
}.getOrElse {
rule.replacement
} }
return replacement
} else { } else {
/* ##match##replace 替换*/ /* ##match##replace 替换*/
kotlin.runCatching { if (regex != null) kotlin.runCatching {
vResult.replace(rule.replaceRegex.toRegex(), rule.replacement) return result.replace(regex, replacement)
}.getOrElse { }
vResult.replace(rule.replaceRegex, rule.replacement) return result.replace(replaceRegex, replacement)
}
}
private fun compileRegexCache(regex: String): Regex? {
if (regexCache.size > 16) {
return try {
regex.toRegex()
} catch (e: Exception) {
null
}
}
if (regexCache.containsKey(regex)) {
return regexCache[regex]
}
return regexCache.getOrPut(regex) {
try {
regex.toRegex()
} catch (e: Exception) {
null
} }
} }
return vResult
} }
/** /**