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

如何移除以下Java代码中的[]符号?预期输出为pollTimestamp

Fixing String Removal of Square Brackets in Java

Hey there! The issue with your current code boils down to a key detail about Java's String type—it's immutable. When you call replaceAll(), it doesn't modify the original string; instead, it creates and returns a brand new string with the changes applied. Your code is discarding this new string, which is why you still see the original [pollTimestamp] output.

Here's the corrected version of your code:

public class HelloWorld{ 
    public static void main(String []args){ 
        String a = "[pollTimestamp]"; 
        // Assign the result of replaceAll back to the variable
        a = a.replaceAll("[^a-zA-Z0-9]",""); 
        System.out.print(a); // This will now output: pollTimestamp
    } 
}

Alternative Approach (Targeted Replacement)

If you only want to remove square brackets (and leave other non-alphanumeric characters intact, if any), you can use a more precise regex or chained replace() calls:

Option 1: Chained replace() (easier to read for simple cases)

public class HelloWorld{ 
    public static void main(String []args){ 
        String a = "[pollTimestamp]"; 
        a = a.replace("[", "").replace("]", "");
        System.out.print(a); // Output: pollTimestamp
    } 
}

Option 2: Regex targeting only square brackets

public class HelloWorld{ 
    public static void main(String []args){ 
        String a = "[pollTimestamp]"; 
        // Escape [] because they have special meaning in regex
        a = a.replaceAll("[\\[\\]]", "");
        System.out.print(a); // Output: pollTimestamp
    } 
}

All these approaches will give you the expected pollTimestamp output. Pick the one that best fits your broader use case—if you need to strip all non-alphanumeric characters, stick with your original regex (just remember to assign the result back!). If you only need to remove brackets, the targeted methods are cleaner.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 21:02:40