You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不区分大小写匹配字符串并为匹配结果添加<mark>标签

Hey there! I totally get why this might feel tricky at first—case-insensitive matching plus wrapping matches in a custom tag requires a bit of regex finesse, but it's totally doable. Let me break this down for you with examples in a couple of common languages:

Python Implementation

Python's re module makes this straightforward with the re.sub function and the IGNORECASE flag. The key here is to preserve the original case of the matched text while wrapping it in your <mark> tag:

import re

original_string = "Hello and good morning world."
search_term = "Good"

# Escape the search term to handle any regex special characters
escaped_term = re.escape(search_term)
# Use a lambda to wrap the matched text (preserving its original case)
result = re.sub(escaped_term, lambda match: f"<mark>{match.group()}</mark>", original_string, flags=re.IGNORECASE)

print(result)
# Output: Hello and <mark>good</mark> morning world.

JavaScript Implementation

For JavaScript, you'll use the String.replace() method with a case-insensitive, global regex. Again, we'll preserve the original case of the matched text:

const originalStr = "Hello and good morning world.";
const searchTerm = "Good";

// Escape special regex characters in the search term
const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Create a regex with global (g) and case-insensitive (i) flags
const matchRegex = new RegExp(escapedTerm, 'gi');
// Replace matches using $& to reference the exact matched text
const result = originalStr.replace(matchRegex, '<mark>$&</mark>');

console.log(result);
// Output: Hello and <mark>good</mark> morning world.

Key Notes to Remember

  • Escape your search term: If your search term includes regex special characters (like ., *, or ?), escaping ensures they're treated as literal characters instead of regex syntax.
  • Preserve original case: Using the matched text itself (via match.group() in Python or $& in JavaScript) means you don't overwrite the original case of the text in your string.
  • Global matching: If your string might have multiple instances of the search term, make sure to enable global matching (the g flag in JavaScript; Python's re.sub does this by default).

内容的提问来源于stack exchange,提问作者Ling Vu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:42:33