I want to remove all special characters from a string,i tried many options which were given in stackoverflow, but none of them work for me.
here is my code :
public class convert {
public static void main(String[] args) {
try {
List<List<String>> outerList = new ArrayList<List<String>>();
outerList.add(new ArrayList<String>(asList("11-","2")));
outerList.add(new ArrayList<String>(asList("(2^","1")));
outerList.add(new ArrayList<String>(asList("11","3)")));
int i,j;
for(i=0;i<outerList.size();i++){
for(j=0;j<outerList.get(0).size();j++){
outerList.get(i).get(j).replaceAll("[^\\w\\s]", "");
if(outerList.get(i).get(j).matches("-?\\d+"){
continue;
}else{
System.out.println("special characters not removed");
System.exit(0);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The (simple) error is that s.replaceAll(...)
does not change s
but yields a new changed string:
String s = outerList.get(i).get(j).replaceAll("[^\\w\\s]", "");
outerList.get(i).set(j, s);
in the case of not alphanumeric you can use
String value = "hello@() world";
value = value.replaceAll("[^A-Za-z0-9]", "");
System.out.println(value) // => helloworld
something similar has already been asked here
Use StringUtils
at Apache Commons Lang ( http://commons.apache.org/proper/commons-lang/ ):
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
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.