2015-09-07 11:44:36 -06:00
|
|
|
// strings/TheReplacements.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.regex.*;
|
2015-12-06 11:45:16 -08:00
|
|
|
import java.nio.file.*;
|
|
|
|
import java.util.stream.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
/*! Here's a block of text to use as input to
|
|
|
|
the regular expression matcher. Note that we
|
|
|
|
first extract the block of text by looking for
|
|
|
|
the special delimiters, then process the
|
|
|
|
extracted block. !*/
|
|
|
|
|
|
|
|
public class TheReplacements {
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void
|
|
|
|
main(String[] args) throws Exception {
|
2015-12-06 11:45:16 -08:00
|
|
|
String s = Files.lines(
|
|
|
|
Paths.get("TheReplacements.java"))
|
|
|
|
.collect(Collectors.joining("\n"));
|
2015-06-15 17:47:35 -07:00
|
|
|
// Match the specially commented block of text above:
|
2015-12-06 11:45:16 -08:00
|
|
|
Matcher mInput = Pattern.compile(
|
|
|
|
"/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
|
2015-06-15 17:47:35 -07:00
|
|
|
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)^ +", "");
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(s);
|
2015-06-15 17:47:35 -07:00
|
|
|
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);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(sbuf);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Here's a block of text to use as input to
|
|
|
|
the regular expression matcher. Note that we
|
|
|
|
first extract the block of text by looking for
|
|
|
|
the special delimiters, then process the
|
|
|
|
extracted block.
|
|
|
|
H(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tO
|
|
|
|
thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE
|
|
|
|
fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr
|
|
|
|
thE spEcIAl dElImItErs, thEn prOcEss thE
|
|
|
|
ExtrActEd blOck.
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|