How to find dotted word with regex in Java?

I am new to Java. I want to find a string in a text file. Suppose the file contains:

Hi, I am learning Java.

I use this template below to search through each exact word.

Pattern p = Pattern.compile("\\b"+search string+"\\b", Pattern.CASE_INSENSITIVE);

It works fine, but does not find "java". How to find both patterns. that is, with boundary characters and with "." at the end of the line. Does anyone have any ideas on how I can solve this problem?

+5
source share
3 answers

, . RegEx: \\.. , . , \\.

, 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());
    }
}

: 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());
    }
}

: 17 java. ( )

EDIT: , , , - , \\.

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());
    }
}
+3
"\\b" + searchstring + "(?:\\.|\\b)"

, ,

"\\b" + searchstring + "(?:\\.(?=\\W|$)|\\b)"
0
Pattern p = Pattern.compile(".*\\W*" + searchWord + "\\W*.*", Pattern.CASE_INSENSITIVE);

To be absolutely sure, the above said: “Find me some text that starts with 0 or more characters, followed by 0 or more characters without words (\ W * is the word boundary), followed by the search word, and then the following a word boundary followed by something else. "

This will be used for situations where the search word is at the beginning of the file, at the very end or between punctuation, for example: "hello, I'm learning, java".

Hope this helps ...

0
source

All Articles