, Scanner.
data.txt :
import java.io.*;
import java.util.Scanner;
import java.util.regex.MatchResult;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("data.txt"));
while (null != s.findWithinHorizon("(?i)\\bjava\\b", 0)) {
MatchResult mr = s.match();
System.out.printf("Word found: %s at index %d to %d.%n", mr.group(),
mr.start(), mr.end());
}
s.close();
}
}
:
Word found: Java at index 74 to 78.
Word found: java at index 153 to 157.
Word found: Java at index 279 to 283.
, , (?i)\bjava\b, :
If the search request comes from a user or if for any other reason, may contain special characters, I suggest you use \Qand \Earound the line, because he quotes all characters between them (and if you are really picky, make sure that the entrance is free \E).
source
share