Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 859
  • Last Modified:

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.
0
go4java
Asked:
go4java
  • 4
  • 3
2 Solutions
 
CEHJCommented:
s = s.replaceAll("[\\.:;\\-\\{\\]\\(\\)]", " ");
0
 
go4javaAuthor Commented:
ok. and the file solution?
0
 
objectsCommented:
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now