简体   繁体   中英

Java Character removal of a string

How should I go about removing the two characters "[" and "]" from a string

Example: [45.677]

Desired: 45.677

I would preferably like to preform this in on single handed method call. Moreover, Not two str.replace() calls.

使用正则表达式

string.replaceAll("\\[|\\]","");

use below regex:

 System.out.println( "[45.677]".replaceAll("\\[|]",""));

as [ is a special character(meta character) you should escape it with backslash in order to treat it as a normal character. thus \\\\[

除了使用replaceAll ,如果[]字符始终位于同一位置(字符串的开头和结尾),则还可以使用:

string.substring(1, string.length() - 1);

尝试这个

System.out.println("[45.677]".replaceAll("[\\[\\]]", ""));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM