Hi,

I need to eliminate all special characters in my file except "space" .. Please check the program below and tell me what I need to change

import java.io.*;
import java.util.Scanner;
public class TestScript	
{
	public static void main(String args[]) throws Exception
	{
		System.out.println("Please Enter the filename\n");
		Scanner sc = new Scanner(System.in);
		String filename=sc.nextLine();
		BufferedReader br =new BufferedReader(new FileReader(filename));
		String str;
		BufferedWriter br1= new BufferedWriter(new FileWriter("textfile1.txt"));
		while((str=br.readLine())!=null)
		{
			String pattern= "[^(A-Z||a-z||\t||[0-9])";
			String p=str.replaceAll(pattern,"");
			br1.write(p);
			br1.newLine();
			br1.flush();
		}
		br.close();
		br1.close();
		File f = new File(filename);
		boolean bol = f.delete();
		File f1 = new File("textfile1.txt");
		f1.renameTo(new File(filename));
	}	
}

Actually the space is also being eliminated .. Is there any problem with it?

Thanks,

Recommended Answers

All 4 Replies

What do you mean when you say "special characters"?
And what do you mean when you say "space"?

Try this as your pattern -> [^A-Za-z\\s0-9] ( '\s' means space, tab, newline etc... )

Useful link -> http://download.oracle.com/javase/tutorial/essential/regex/

Wht do I do if I have to keep only one space and deleted the remaining spaces

For example if its "asdf asdf". Then how can i get it to look like
"asdf asdf".

Sorry but actually the above post intended to have multiple spaces between the two words but the post edited it to a single space ... I want to do exactly the samething. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.