| Refresh | Home EGTry.com

convert one string to another with regex pattern


package egtry.string;

public class Replace {

	public static void main(String[] args) {

	//replace all instance of a character with another
	//e.g. replace space with underscore
	String oldString="This one has some spaces";
	String newString=oldString.replace(' ', '_');
	System.out.println(oldString+" => "+newString);

	//replace some pattern of subtring with another
	
	//replace any character that are not letter and digit to underscore,
        // and convert a continuous nultiple underscore to one
	String filename="old school                  v1 .      3     . 3 .jar";
	String newFilename=filename.replaceAll("[^a-zA-Z0-9]+", "_");
	System.out.println(filename+" => "+newFilename);
	
	
	//remove all whitespace, tab and newline in string
	String line="this you a multiple	line paragraph\n	The second one";
	String newLine=line.replaceAll("\\s+", "");
	System.out.println(line+" => "+newLine);
	}

}


output

This one has some spaces => This_one_has_some_spaces
old school                  v1 .      3     . 3 .jar => old_school_v1_3_3_jar
this you a multiple	line paragraph
	The second one => thisyouamultiplelineparagraphThesecondone