0

I am having a group of strings in Arraylist.

I want to remove all the strings with only numbers and also strings like this : (0.75%),$1.5 ..basically everything that does not contain the characters. 2) I want to remove all special characters in the string before i write to the console. "God should be printed God. "Including should be printed: quoteIncluding 'find should be find

3
  • 1
    I smell regex. Commented May 12, 2011 at 5:45
  • "..everything that does not contain characters.." That is the clue! Instead of thinking of 'removing' why not thinking of 'including', A-Z and a-z is only 26 + 26 alphabets you know.. Commented May 12, 2011 at 5:52
  • What have you attempted so far? Commented May 12, 2011 at 6:21

2 Answers 2

1

Java boasts a very nice Pattern class that makes use of regular expressions. You should definitely read up on that. A good reference guide is here.

I was going to post a coding solution for you, but styfle beat me to it! The only thing I was going to do different here was within the for loop, I would have used the Pattern and Matcher class, as such:

for(int i = 0; i < myArray.size(); i++){
    Pattern p = Pattern.compile("[a-z][A-Z]");
    Matcher m = p.matcher(myArray.get(i));
    boolean match = m.matches();  
    //more code to get the string you want
}

But that too bulky. styfle's solution is succinct and easy.

Sign up to request clarification or add additional context in comments.

Comments

0

When you say "characters," I'm assuming you mean only "a through z" and "A through Z." You probably want to use Regular Expressions (Regex) as D1e mentioned in a comment. Here is an example using the replaceAll method.

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>(5);
        list.add("\"God");
        list.add("&quot;Including");
        list.add("'find");
        list.add("24No3Numbers97");
        list.add("w0or5*d;");

        for (String s : list) {
            s = s.replaceAll("[^a-zA-Z]",""); //use whatever regex you wish
            System.out.println(s);
        }
    }
}

The output of this code is as follows:

God
quotIncluding
find
NoNumbers
word

The replaceAll method uses a regex pattern and replaces all the matches with the second parameter (in this case, the empty string).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.