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

如何用正则表达式移除嵌套的/*与*/之间的子串?

Solution for Removing Nested /* */ Comments

Got it, I totally get why basic approaches fail here—nested C-style comments are a classic gotcha because simple regex or naive string parsing can't track the depth of nested comment blocks. Let's break down a reliable solution that handles even the trickiest nested cases.

Example Input & Expected Output

Input:

const x = 5; /* Initialize x /* this is a nested comment */ with a value */ const y = 10;

Expected Output:

const x = 5;  const y = 10;

This method works across most programming languages and reliably handles nested comments by tracking whether we're inside a comment, and how deep the nesting is. Here's a Python implementation as an example:

def remove_nested_comments(text):
    result = []
    in_comment = False
    comment_depth = 0
    
    i = 0
    while i < len(text):
        if not in_comment:
            # Look for the start of a comment
            if text[i:i+2] == '/*':
                in_comment = True
                comment_depth += 1
                i += 2  # Skip the /*
            else:
                result.append(text[i])
                i += 1
        else:
            # Look for the end of a comment
            if text[i:i+2] == '*/':
                comment_depth -= 1
                if comment_depth == 0:
                    in_comment = False
                i += 2  # Skip the */
            elif text[i:i+2] == '/*':
                # Found another nested comment start
                comment_depth += 1
                i += 2
            else:
                i += 1  # Skip characters inside comments
    
    return ''.join(result)

How This Works

  • We maintain two state variables: in_comment (tracks if we're inside any comment) and comment_depth (tracks how many nested comments we're in).
  • When we hit /*, we increment the depth and enter comment mode.
  • When we hit */, we decrement the depth—only when the depth hits 0 do we exit comment mode.
  • All characters outside comment mode are added to the result; characters inside are skipped entirely.

Alternative: Recursive Regex (For Languages That Support It)

If you're using a language with regex engines that support recursion (like JavaScript ES2018+, PHP with PCRE, or Ruby), you can use a recursive regex pattern. For example, in JavaScript:

function removeNestedComments(text) {
    // Recursive regex to match nested /* */ comments
    const commentRegex = /\/\*(?:[^*]|\*(?!\/)|(?R))*\*\//gs;
    return text.replace(commentRegex, '');
}

This regex uses (?R) to recursively match the entire comment pattern, allowing it to handle nested blocks. Note that this won't work in languages with limited regex support (like Python's default re module).


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:13:14