A Block of Text as the Replacement of the Regular Expression Matcher

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - A Block of Text as the Replacement of the Regular Expression Matcher

This is a example of Java program.

[edit] Java Source Code

  • Package: com.bruceeckel
  • File: TheReplacements.java
package com.bruceeckel;
 
//: c12:TheReplacements.java
//From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
//www.BruceEckel.com. See copyright notice in CopyRight.txt.
//Modified by Code Panda.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/*
 * ! Here's a block of text to use as input to the regular expression matcher.
 * Note that we'll first extract the block of text by looking for the special
 * delimiters, then process the extracted block. !
 */
 
public class TheReplacements {
    public static void main(String[] args) throws Exception {
	//Modified by Code Panda.
	//In order to run this program with Eclipse, we should give the parameter an absolute path.
	String pathBase = "C:\\exampleshow\\";
	String s = TextFile.read(pathBase + "TheReplacements.java");
	// Match the specially-commented block of text above:
	Matcher mInput = Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
	if (mInput.find())
	    s = mInput.group(1); // Captured by parentheses
	// Replace two or more spaces with a single space:
	s = s.replaceAll(" {2,}", " ");
	// Replace one or more spaces at the beginning of each
	// line with no spaces. Must enable MULTILINE mode:
	s = s.replaceAll("(?m)^ +", "");
	System.out.println(s);
	s = s.replaceFirst("[aeiou]", "(VOWEL1)");
	StringBuffer sbuf = new StringBuffer();
	Pattern p = Pattern.compile("[aeiou]");
	Matcher m = p.matcher(s);
	// Process the find information as you
	// perform the replacements:
	while (m.find())
	    m.appendReplacement(sbuf, m.group().toUpperCase());
	// Put in the remainder of the text:
	m.appendTail(sbuf);
	System.out.println(sbuf);
 
    }
} // /:~
 
class TextFile extends ArrayList {
    // Tools to read and write files as single strings:
    public static String read(String fileName) throws IOException {
	StringBuffer sb = new StringBuffer();
	System.out.println("try to read text from "+fileName+" ...");
	BufferedReader in = new BufferedReader(new FileReader(fileName));
	String s;
	while ((s = in.readLine()) != null) {
	    sb.append(s);
	    sb.append("\n");
	}
	in.close();
	return sb.toString();
    }
 
    public static void write(String fileName, String text) throws IOException {
	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
	out.print(text);
	out.close();
    }
 
    public TextFile(String fileName) throws IOException {
	super(Arrays.asList(read(fileName).split("\n")));
    }
 
    public void write(String fileName) throws IOException {
	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
	for (int i = 0; i < size(); i++)
	    out.println(get(i));
	out.close();
    }
 
    // Simple test:
    public static void main(String[] args) throws Exception {
	//Modified by Code Panda.
	//In order to run this program with Eclipse, we should give the parameter an absolute path.
	String pathBase = "C:\\exampleshow\\";
	String file = read(pathBase+"HelloExampleShow.java");
	write(pathBase + "test.txt", file);
	TextFile text = new TextFile(pathBase + "test.txt");
	text.write(pathBase + "test2.txt");
    }
}

[edit] What Result You Can Get

Run the program, you will get:


try to read text from C:\exampleshow\TheReplacements.java ...
package com.bruceeckel;

//: c12:TheReplacements.java
//From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
//www.BruceEckel.com. See copyright notice in CopyRight.txt.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
* ! Here's a block of text to use as input to the regular expression matcher.
* Note that we'll first extract the block of text by looking for the special
* delimiters, then process the extracted block. !
*/

public class TheReplacements {
public static void main(String[] args) throws Exception {
	String pathBase = "C:\\exampleshow\\";
	String s = TextFile.read(pathBase + "TheReplacements.java");
	// Match the specially-commented block of text above:
	Matcher mInput = Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
	if (mInput.find())
	 s = mInput.group(1); // Captured by parentheses
	// Replace two or more spaces with a single space:
	s = s.replaceAll(" {2,}", " ");
	// Replace one or more spaces at the beginning of each
	// line with no spaces. Must enable MULTILINE mode:
	s = s.replaceAll("(?m)^ +", "");
	System.out.println(s);
	s = s.replaceFirst("[aeiou]", "(VOWEL1)");
	StringBuffer sbuf = new StringBuffer();
	Pattern p = Pattern.compile("[aeiou]");
	Matcher m = p.matcher(s);
	// Process the find information as you
	// perform the replacements:
	while (m.find())
	 m.appendReplacement(sbuf, m.group().toUpperCase());
	// Put in the remainder of the text:
	m.appendTail(sbuf);
	System.out.println(sbuf);

}
} // /:~

class TextFile extends ArrayList {
// Tools to read and write files as single strings:
public static String read(String fileName) throws IOException {
	StringBuffer sb = new StringBuffer();
	System.out.println("try to read text from "+fileName+" ...");
	BufferedReader in = new BufferedReader(new FileReader(fileName));
	String s;
	while ((s = in.readLine()) != null) {
	 sb.append(s);
	 sb.append("\n");
	}
	in.close();
	return sb.toString();
}

public static void write(String fileName, String text) throws IOException {
	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
	out.print(text);
	out.close();
}

public TextFile(String fileName) throws IOException {
	super(Arrays.asList(read(fileName).split("\n")));
}

public void write(String fileName) throws IOException {
	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
	for (int i = 0; i < size(); i++)
	 out.println(get(i));
	out.close();
}

// Simple test:
public static void main(String[] args) throws Exception {
	String pathBase = "C:\\exampleshow\\";
	String file = read(pathBase+"HelloExampleShow.java");
	write(pathBase + "test.txt", file);
	TextFile text = new TextFile(pathBase + "test.txt");
	text.write(pathBase + "test2.txt");
}
}

p(VOWEL1)ckAgE cOm.brUcEEckEl;

//: c12:ThEREplAcEmEnts.jAvA
//FrOm 'ThInkIng In JAvA, 3rd Ed.' (c) BrUcE EckEl 2002
//www.BrUcEEckEl.cOm. SEE cOpyrIght nOtIcE In COpyRIght.txt.

ImpOrt jAvA.IO.BUffErEdREAdEr;
ImpOrt jAvA.IO.BUffErEdWrItEr;
ImpOrt jAvA.IO.FIlEREAdEr;
ImpOrt jAvA.IO.FIlEWrItEr;
ImpOrt jAvA.IO.IOExcEptIOn;
ImpOrt jAvA.IO.PrIntWrItEr;
ImpOrt jAvA.UtIl.ArrAyLIst;
ImpOrt jAvA.UtIl.ArrAys;
ImpOrt jAvA.UtIl.rEgEx.MAtchEr;
ImpOrt jAvA.UtIl.rEgEx.PAttErn;

/*
* ! HErE's A blOck Of tExt tO UsE As InpUt tO thE rEgUlAr ExprEssIOn mAtchEr.
* NOtE thAt wE'll fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr thE spEcIAl
* dElImItErs, thEn prOcEss thE ExtrActEd blOck. !
*/

pUblIc clAss ThEREplAcEmEnts {
pUblIc stAtIc vOId mAIn(StrIng[] Args) thrOws ExcEptIOn {
	StrIng pAthBAsE = "C:\\ExAmplEshOw\\";
	StrIng s = TExtFIlE.rEAd(pAthBAsE + "ThEREplAcEmEnts.jAvA");
	// MAtch thE spEcIAlly-cOmmEntEd blOck Of tExt AbOvE:
	MAtchEr mInpUt = PAttErn.cOmpIlE("/\\*!(.*)!\\*/", PAttErn.DOTALL).mAtchEr(s);
	If (mInpUt.fInd())
	 s = mInpUt.grOUp(1); // CAptUrEd by pArEnthEsEs
	// REplAcE twO Or mOrE spAcEs wIth A sInglE spAcE:
	s = s.rEplAcEAll(" {2,}", " ");
	// REplAcE OnE Or mOrE spAcEs At thE bEgInnIng Of EAch
	// lInE wIth nO spAcEs. MUst EnAblE MULTILINE mOdE:
	s = s.rEplAcEAll("(?m)^ +", "");
	SystEm.OUt.prIntln(s);
	s = s.rEplAcEFIrst("[AEIOU]", "(VOWEL1)");
	StrIngBUffEr sbUf = nEw StrIngBUffEr();
	PAttErn p = PAttErn.cOmpIlE("[AEIOU]");
	MAtchEr m = p.mAtchEr(s);
	// PrOcEss thE fInd InfOrmAtIOn As yOU
	// pErfOrm thE rEplAcEmEnts:
	whIlE (m.fInd())
	 m.AppEndREplAcEmEnt(sbUf, m.grOUp().tOUppErCAsE());
	// PUt In thE rEmAIndEr Of thE tExt:
	m.AppEndTAIl(sbUf);
	SystEm.OUt.prIntln(sbUf);

}
} // /:~

clAss TExtFIlE ExtEnds ArrAyLIst {
// TOOls tO rEAd And wrItE fIlEs As sInglE strIngs:
pUblIc stAtIc StrIng rEAd(StrIng fIlENAmE) thrOws IOExcEptIOn {
	StrIngBUffEr sb = nEw StrIngBUffEr();
	SystEm.OUt.prIntln("try tO rEAd tExt frOm "+fIlENAmE+" ...");
	BUffErEdREAdEr In = nEw BUffErEdREAdEr(nEw FIlEREAdEr(fIlENAmE));
	StrIng s;
	whIlE ((s = In.rEAdLInE()) != nUll) {
	 sb.AppEnd(s);
	 sb.AppEnd("\n");
	}
	In.clOsE();
	rEtUrn sb.tOStrIng();
}

pUblIc stAtIc vOId wrItE(StrIng fIlENAmE, StrIng tExt) thrOws IOExcEptIOn {
	PrIntWrItEr OUt = nEw PrIntWrItEr(nEw BUffErEdWrItEr(nEw FIlEWrItEr(fIlENAmE)));
	OUt.prInt(tExt);
	OUt.clOsE();
}

pUblIc TExtFIlE(StrIng fIlENAmE) thrOws IOExcEptIOn {
	sUpEr(ArrAys.AsLIst(rEAd(fIlENAmE).splIt("\n")));
}

pUblIc vOId wrItE(StrIng fIlENAmE) thrOws IOExcEptIOn {
	PrIntWrItEr OUt = nEw PrIntWrItEr(nEw BUffErEdWrItEr(nEw FIlEWrItEr(fIlENAmE)));
	fOr (Int I = 0; I < sIzE(); I++)
	 OUt.prIntln(gEt(I));
	OUt.clOsE();
}

// SImplE tEst:
pUblIc stAtIc vOId mAIn(StrIng[] Args) thrOws ExcEptIOn {
	StrIng pAthBAsE = "C:\\ExAmplEshOw\\";
	StrIng fIlE = rEAd(pAthBAsE+"HEllOExAmplEShOw.jAvA");
	wrItE(pAthBAsE + "tEst.txt", fIlE);
	TExtFIlE tExt = nEw TExtFIlE(pAthBAsE + "tEst.txt");
	tExt.wrItE(pAthBAsE + "tEst2.txt");
}
}



[edit] Required External Libraries and/or Files for this Java Example

In order to run this example, you should make a folder as C:\exampleshow, and copy TheReplacements.java into it.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools