如何移除以下Java代码中的[]符号?预期输出为pollTimestamp
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

