본문 바로가기

자바

[Java] Regular Expression

 

Find out if there are any occurrences of the word "w3schools" in a sentence

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyClass {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("Visit W3Schools!");
    boolean matchFound = matcher.find();
    if(matchFound) {
      System.out.println("Match found");
    } else {
      System.out.println("Match not found");
    }
  }
}

 

Note: If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape them. In Java, backslashes in strings need to be escaped themselves, so two backslashes are needed to escape special characters. For example, to search for one or more question marks you can use the following expression: "\\?"

'자바' 카테고리의 다른 글

Class ServerSocket  (0) 2020.10.28
Package java.net  (0) 2020.10.28
daemon thread  (0) 2020.10.22
[Java] Thread 문제점  (0) 2020.10.22
[Java] Thread (api 8)  (0) 2020.10.22