不支持ios正则表达式lookbehind

问题描述 投票:0回答:1

我正在使用正则表达式来搜索 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 中收到以下错误:无效的正则表达式:无效的组说明符名称

我读过有关放置(?

改变了

(?<!</

进入

(?:</

现在它不再匹配任何东西了

javascript regex safari lookbehind
1个回答
0
投票

你可以尝试:

  • 解决方案 1:逃避 <(假设向前看不是问题)
  • 解决方案2:删除前瞻,只调用组捕获。因为使用捕获组时不需要使用前瞻。

示例:

<!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>
``
© www.soinside.com 2019 - 2024. All rights reserved.