Java Reference
In-Depth Information
Input: Do me a favor? Fetch my favorite.
ReplaceAll: Do me a favour? Fetch my favorite.
Append methods: Do me a favour? Fetch my favorite.
Printing All Occurrences of a Pattern
Problem
You need to find all the strings that match a given regex in one or more files or other sources.
Solution
This example reads through a file one line at a time. Whenever a match is found, I extract it
from the line and print it.
This code takes the group() methods from Finding the Matching Text , the substring meth-
od from the CharacterIterator interface, and the match() method from the regex and
simply puts them all together. I coded it to extract all the “names” from a given file; in run-
ning the program through itself, it prints the words import , java , until , regex , and so on,
each on its own line:
C:\\> javac -d . ReaderIter.java
C:\\> java regex.ReaderIter ReaderIter.java
import
java
util
regex
import
java
io
Print
all
the
strings
that
match
given
pattern
from
file
Search WWH ::




Custom Search