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

如何在PostgreSQL中移除字符串里/*与*/之间的内容

移除字符串中/与/之间的注释内容

核心思路

通过正则匹配/*开头到*/结尾的块注释内容(包含标记本身),将其替换为空字符串,即可得到目标结果。

代码实现示例

Python 版本

import re

def remove_block_comments(text):
    # 匹配/*到*/的内容,支持单行和多行注释,非贪婪模式避免过度匹配
    return re.sub(r'/\*.*?\*/', '', text)

# 测试示例
original_text = "select * from food where /* id = 1 and */ food_code = 2"
processed_text = remove_block_comments(original_text)
print(processed_text)
# 输出: select * from food where  food_code = 2

JavaScript 版本

function removeBlockComments(text) {
    // [\s\S]匹配所有字符(包括换行),非贪婪模式适配多行注释
    return text.replace(/\/\*[\s\S]*?\*\//g, '');
}

// 测试示例
const originalText = "select * from food where /* id = 1 and */ food_code = 2";
const processedText = removeBlockComments(originalText);
console.log(processedText);
// 输出: select * from food where  food_code = 2

注意事项

  • 上述正则采用非贪婪匹配,能正确处理单行和多行的块注释
  • 若字符串中存在嵌套块注释(如/* 外层注释 /* 内层注释 */ 剩余内容 */),正则无法准确解析,这种场景需要通过状态机逐字符遍历处理

内容的提问来源于stack exchange,提问作者AliReza Tavakoliyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:38:13