2

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();
        }
    }
} 
user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62
Anoop Dobhal
  • 107
  • 1
  • 3
  • 12

3 Answers3

5

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);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

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

Community
  • 1
  • 1
Enermis
  • 679
  • 1
  • 5
  • 16
-3

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

eruiz
  • 1,963
  • 1
  • 14
  • 22