Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the word with dot using regex in Java?

Tags:

java

regex

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?

like image 911
Vijay Anand Avatar asked Oct 05 '22 23:10

Vijay Anand


1 Answers

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:

  • Using Regular Expressions in Java
  • Java Regex Tutorial
  • Java Regular Expressions

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());
    }
}
like image 127
Luiggi Mendoza Avatar answered Oct 13 '22 12:10

Luiggi Mendoza