gpt4 book ai didi

php - 将 "//"注释与正则表达式匹配但不在引号内

转载 作者:行者123 更新时间:2023-12-01 15:53:34 26 4
gpt4 key购买 nike

我需要匹配和替换一些评论。例如:

$test = "the url is http://www.google.com";// comment "<-- that quote needs to be matched

我想匹配引号外的注释,并将注释中的任何 " 替换为 "

我尝试了多种模式和不同的运行方式,但都没有成功。

正则表达式将使用 javascript 运行以匹配 php "//"注释

更新:我从下面的 borkweb 中获取了正则表达式并对其进行了修改。使用了 http://ejohn.org/blog/search-and-dont-replace/ 中的函数并想出了这个:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function t_replace(data){
var q = {}, ret = "";
data.replace(/(?:((["'\/]*(("[^"]*")|('[^']*'))?[\s]*)?[\/\/|#][^"|^']*))/g, function(value){
q[key] = value;
});
for ( var key in q ){
ret = q[key];
}
var text = data.split(ret);
var out = ret + text[1];
out = out.replace(/"/g,"&quot;");
out = out.replace(/'/g,"&apos;");
return text[0] + out;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(t_replace("$test = \"the url is http://www.google.com\";// c'o\"mment \"\"\"<-- that quote needs to be matched")+"<br>");
document.write(t_replace("$test = 'the url is http://www.google.com';# c'o\"mment \"\"\"<-- that quote needs to be matched"));
</script>
</body>
</html>

它处理单引号或双引号之外的所有行注释。无论如何我可以优化这个功能?

更新 2:它不处理这个字符串

document.write(t_replace("$test //= \"the url is http://www.google.com\"; //c'o\"mment \"\"\"<-- that quote needs to be matched")+"<br>");

最佳答案

您可以使用正则表达式同时匹配所有字符串和注释。如果是字符串,可以原封不动的替换成它本身,然后处理一个特殊的情况进行注释。

我想出了这个正则表达式:

"(\\[\s\S]|[^"])*"|'(\\[\s\S]|[^'])*'|(\/\/.*|\/\*[\s\S]*?\*\/)

有3个部分:

  • "(\\[\s\S]|[^"])*" 用于匹配双引号字符串。
  • '(\\[\s\S]|[^'])*' 用于匹配单引号字符串。
  • (\/\/.*|\/\*[\s\S]*?\*\/) 用于匹配单行和多行注释。

替换函数检查匹配的字符串是否为注释。如果不是,请不要更换。如果是,请替换 "'

function t_replace(data){
var re = /"(\\[\s\S]|[^"])*"|'(\\[\s\S]|[^'])*'|(\/\/.*|\/\*[\s\S]*?\*\/)/g;
return data.replace(re, function(all, strDouble, strSingle, comment) {
if (comment) {
return all.replace(/"/g, '&quot;').replace(/'/g, '&apos;');
}
return all;
});
}

测试运行:

Input: $test = "the url is http://www.google.com";// c'o"mment """<-- that quote needs to be matched
Output: $test = "the url is http://www.google.com";// c&apos;o&quot;mment &quot;&quot;&quot;<-- that quote needs to be matched

Input: $test = 'the url is http://www.google.com';# c'o"mment """<-- that quote needs to be matched
Output: $test = 'the url is http://www.google.com';# c'o"mment """<-- that quote needs to be matched

Input: $test //= "the url is http://www.google.com"; //c'o"mment """<-- that quote needs to be matched
Output: $test //= &quot;the url is http://www.google.com&quot;; //c&apos;o&quot;mment &quot;&quot;&quot;<-- that quote needs to be matched

关于php - 将 "//"注释与正则表达式匹配但不在引号内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4568410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com