정규표현식

최종윤·2023년 7월 5일

자바

목록 보기
4/6

정의

정규표현식은 text를 탐색하거나 replace할 때 사용하기 위한 연속된 문자열 패턴이다.
Pattern class 에서 pattern 정의할 때 ,
Matcher class에서 탐색을 위해
java replace()메서드에서도 사용된다.
java built-in regular expression이 없기 때문에
import java.util.regex;를 해준다.
regex에는 Pattern class ,Matcher class, PatternSyntaxException class가 있다.

Pattern, Matcher 예제

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 Main {
  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");
    }
  }
}
// Outputs Match found

표현방법

split() 에서 여러개의 구분자를 사용하고 싶은 경우 | 를 사용하여 나타내면 됩니다.
0부터 9까지의 문자를 구분자로 사용하고자 한다면, java에서는 |이 비트 연산자이고 ||이 or연산자이지만 , 정규식에서 |이 or연산을 하여
split("0|1|2|3|4|5|6|7|8|9")로 하면 됩니다. 이를 간단히
split("[0-9]")로 표현할 수 있습니다.

Brackets are used to find a range of characters:

Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find one character NOT between the brackets
[0-9] Find one character from the range 0 to 9

Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n

profile
https://github.com/jyzayu

0개의 댓글