Java/Pattern: Search/Replace for invalid characters

Input:

testString = 'this is/[ a .-test s'tring wi"th in)valid ch}aracters'
invalidChars = ".:;-{]()... (ideally to be read from a file/xml)
toBeReplacedBy = ' ' (one white space)

Output:

validatedString = 'this is a test string with invalid characters'


Any sample method with file access (for reading invalidChars)?

Best Rgds.
go4javaAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
BufferedReader in = new BufferedReader(new FileReader(file));
String line = null;
while (null!=(line=in.readLine())
{
   line = line.replaceAll("[\\.:;\\-\\{\\]\\(\\)]", " ");
   // do what you need with line
}
in.close();

0
 
CEHJConnect With a Mentor Commented:
s = s.replaceAll("[\\.:;\\-\\{\\]\\(\\)]", " ");
0
 
go4javaAuthor Commented:
ok. and the file solution?
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
CEHJCommented:
This will clean that particular String:


s = s.replaceAll("[\\.:;\\-}\\[()'\"/]", " ");
0
 
objectsCommented:
The following will do what you need:

      public static String strip(String s, String invalid)
      {
         char[] chars = s.toCharArray();
         StringBuffer result = new StringBuffer();
         for(int i = 0;i<chars.length;i++)
         {
            if (invalid.indexOf(chars[i]))
            {
                // invalid char, do as required
            }
            else
            {
               result.append(chars[i]);
            }
         }
         return result.toString();
      }
0
 
objectsCommented:
to read the invalid chars just use something like:

BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
in.close();
0
 
objectsCommented:
0
 
CEHJCommented:
8-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.