I am a new to Java. I want to search for a string in text file. Suppose the file contains:
Hi, I am learning Java.
I am using this below pattern to search through every exact word.
Pattern p = Pattern.compile("\\b"+search string+"\\b", Pattern.CASE_INSENSITIVE);
It works fine but it doesn't find "java." How to find both patterns. i.e with boundary symbols and with "." at end of the string. Does anyone have any ideas on how I can solve this problem?
You should parse your search string in order to change the dot .
into a RegEx dot: \\.
. Note that a single dot is a metacharacter in Regular Expressions and means any character. For example, you can replace all the dots in your String for \\.
If you don't want to do all that job, then just send java\\.
as your search string
More info:
Code example:
public static void main(String[] args) {
String fileContent = "Hi i am learning java.";
String searchString = "java";
Pattern p = Pattern.compile(searchString);
Matcher m = p.matcher(fileContent );
while(m.find()) {
System.out.println(m.start() + " " + m.group());
}
}
It would print: 17 java
public static void main(String[] args) {
String fileContent = "Hi i am learning java.";
String searchString = "java\\.";
Pattern p = Pattern.compile(searchString);
Matcher m = p.matcher(fileContent );
while(m.find()) {
System.out.println(m.start() + " " + m.group());
}
}
It would print: 17 java.
(note the dot in the end)
EDIT: As a very basic solution, since the only problem you have is with the dot, you can replace all the dots in your string with \\.
public static void main(String[] args) {
String fileContent = "Hi i am learning java.";
String searchString = "java.";
//this will do the trick even if the "searchString" doesn't contain a dot inside
searchString = searchString.replaceAll("\\.", "\\.");
Pattern p = Pattern.compile(searchString);
Matcher m = p.matcher(fileContent );
while(m.find()) {
System.out.println(m.start() + " " + m.group());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With