我正在使用正则表达式来搜索 html 并突出显示结果。除 ios 版本外,它在所有版本中都运行良好 < 16.4 because they dont support regex lookbehind. can someone help me change my regex because i have tried several alternative but they never leave the html image tags alone :-(
const regex = new RegExp('(?<!</?[^>]*|&[^;]*)(' + $search.value + ')', 'gi');
我在 safari 中收到以下错误:无效的正则表达式:无效的组说明符名称
我读过有关放置(?
改变了
(?<!</
进入
(?:</
现在它不再匹配任何东西了
你可以尝试:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Regex Search Demo</title>
</head>
<body>
<p id="content">Hello, this is a sample <a href="#">text</a> for search. Also, here's an &text; entity.</p>
<p>Full match: <span id="fullMatch"></span></p>
<p>Captured group: <span id="capturedGroup"></span></p>
<script>
let $search = { value: "text" };
let str = document.getElementById('content').textContent; // Using textContent to ignore HTML tags
// Create a regex pattern based on $search.value
/* Your regex: */
// let regexPattern = new RegExp('(?<!</?[^>]*|&[^;]*)(' + $search.value + ')', 'gi');
/* Solution 1: escaping the < */
//let regexPattern = new RegExp('(?<!\</?[^>]*|&[^;]*)(' + $search.value + ')', 'gi');
/* Solution 2: without lookahead. Just use the capture group */
let regexPattern = new RegExp('!</?[^>]*|&[^;]*(' + $search.value + ')', 'gi');
// Execute regex pattern
let groupResult = regexPattern.exec(str);
if (groupResult) {
document.getElementById('fullMatch').textContent = groupResult[0]; // Display the full match
if (groupResult[1]) {
document.getElementById('capturedGroup').textContent = groupResult[1]; // Display the captured group
} else {
document.getElementById('capturedGroup').textContent = "No captured group found.";
}
} else {
document.getElementById('fullMatch').textContent = "No match found.";
document.getElementById('capturedGroup').textContent = "No captured group found.";
}
</script>
</body>
</html>
``