我正在尝试构建一个正则表达式,用一些 HTML 标记替换所有符号“$$”,例如 <someTag></someTag>。
我使用这个正则表达式,但它并没有涵盖所有情况:
\$\$(\S[^\*]+\S)\$\$
'aaa $$123$$ c$ ddd'.replace(/\$\$(\S[^\*]+\S)\$\$/g, '<a1>$1</a1>') // works 'aaa $$123$$ c$ $$ddd$$'.replace(/\$\$(\S[^\*]+\S)\$\$/g, '<a1>$1</a1>') // doesn't work, should be 'aaa <a1>123</a1> c$ <a1>ddd</a1>'
console.log('aaa $$123$$ c$ ddd'.replace(/\$\$(\S[^\*]+\S)\$\$/g, '<a1>$1</a1>')) // works
console.log('aaa $$123$$ c$ $$ddd$$'.replace(/\$\$(\S[^\*]+\S)\$\$/g, '<a1>$1</a1>')) // doesn't work, should be 'aaa <a1>123</a1> c$ <a1>ddd</a1>'
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
不是正则表达式解决方案,但它有效。说明:使用分隔符 (
$$) 分割字符串。然后创建一个新字符串result并插入数组的每个部分。然后检查当前索引是奇数还是偶数,并根据情况添加开始标记 (prefix) 或结束标记 (suffix)。我希望这有帮助!function replaceTag(string, delimiter, prefix, suffix){ let parts = string.split(delimiter); let result = ''; for(let index = 0; index ', '')); console.log(replaceTag('aaa $$123$$ c$ $$ddd$$', '$$', '', ' '));最快的方法是使用非贪婪的点全方法:
/\$\$(.*?)\$\$/sghttps://regex101.com/r/upveAX/1
单独使用点总是会更快,因为它不依赖于断言或类结构,
这会增加 3 倍的性能开销。
console.log('aaa $$123$$ c$ ddd'.replace(/\$\$(.*?)\$\$/sg, '$1 '));
console.log('aaa $$123$$ c$ $$ddd$$'.replace(/\$\$(.*?)\$\$/sg, '$1 '));