Charlie Brown
Charlie Brown

Reputation: 183

Pass only valid characters in java

I want to do something like this:

String myString="123EDCBAabcde";
myString=myString.passValidChars("ABCDE");

now myString is "EDCBA"

Is there already a function which only passes the valid characters and removes the others? If not what is the best way to do this?

Best Regards.

Upvotes: 0

Views: 1083

Answers (6)

Ventsislav Marinov
Ventsislav Marinov

Reputation: 604

String string = "123EDCBAabcde";

Pattern pattern = Pattern.compile("[ABCDE]");
Matcher mach = pattern.matcher(string);

StringBuffer str = new StringBuffer();
while(mach.find()){
    str.append(mach.group());
}
string = str.toString(); // Now string is "EDCBA"

Upvotes: 1

Wojciech Owczarczyk
Wojciech Owczarczyk

Reputation: 5735

myString = myString.replaceAll("[^ABCDE.]+", "");

Upvotes: 4

JohnJohnGa
JohnJohnGa

Reputation: 15685

Related to @JB Nizet answer:

    static String passValidChar(String in, String validChar){
        StringBuilder strBuilder = new StringBuilder();
        for(char c : in.toCharArray()){
            if(validChar.indexOf(String.valueOf(c)) != -1){
                strBuilder.append(c);
            }
        }
        return strBuilder.toString();
    }

    public static void main(String [] args){
        System.out.println(passValidChar("123EDCBAabcde", "EDCBA"));    
    }

Upvotes: 0

S.831
S.831

Reputation: 123

Pattern.compile("[^A-Z]").matcher(myString).replaceAll("")

Upvotes: 0

RokL
RokL

Reputation: 2812

Guava library (google collections) has the exact class you need: CharMatcher

http://guava-libraries.googlecode.com/files/Guava_for_Netflix_.pdf

Pages 12 up to 19.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691963

This is trival to implement.

  • Start with an empty StringBuilder.
  • Iterate through each char of myString.
  • If the char is contained in the String of valid chars, add it to the StringBuilder.
  • Convert the StringBuilder to a String.
  • Done.

Upvotes: 3

Related Questions