정규 표현식: Pattern & Matcher

Nadia·2024년 2월 6일

Java

목록 보기
3/4

정규 표현식 (Regular Expression)

: [특정 패턴의 문자열]을 검색하는 도구




Pattern

: 정규 표현식이 컴파일(Compile) 된 클래스
-문자열을 검증하거나, 활용하기 위해 사용

static Pattern complie(String regex)
: 해당 정규식을 갖는 패턴 생성
String pattern()
: 컴파일 된 정규식 반환
Matcher matcher(CharSequence input)
: 패턴에 매칭할 문자열을 입력하여 Matcher 생성
static boolean matches(String regex, CharSequence input)
: 정규식과 문자열이 일치하는지 확인
String[] split(CharSequence input) 
: 패턴이 일치하는 항목을 중심으로 input을 분할
String[] splie(CharSequence input, int limit)
: (limit - 1)의 횟수만큼 패턴을 일치시켜 문자열 자르기 
(만약 0 이하라면 최대한 많이 적용)

Q. Charsequence와 String의 차이?

String

  • 마크업 문자를 입력하여 사용할 수 없는 문자열 (변경금지 문자)
  • 불변(immutable), 한 번 생성되면 변경할 수 없다.
  • String 객체를 수정하거나 문자열을 연결, 분할하려면 새로운 String 객체를 생성해야 한다.

CharSequence

  • 마크업 문자를 사용하여 변형과 가공이 가능한 문자열
  • 문자열의 읽기 전용 시퀀스를 나타내는 인터페이스
  • CharSequence를 구현한 클래스들은 문자열을 저장하고 조작할 수 있다.
  • CharSequence를 사용하면 String 이외의 다른 클래스(예: StringBuilder)도 사용할 수 있다.
  • 문자열을 수정하지 않고도 문자열 조작 메서드를 호출할 수 있다.



Matcher

: Pattern 클래스를 받아 대상 문자열과 패턴이 일치하는 부분을 찾아 boolean으로 반환

Pattern pattern()
: matcher가 해석한 패턴을 반환
Metcher userPattern(Pattern newPattern)
: matcher가 사용할 Pattern을 변경
Matcher reset(CharSequence input)
: matcher가 분석할 문자열을 변경
int start()
: 매칭된 문자열의 시작 index 반환
int start(int i)
: 매칭된 문자열의 i번째 문자열의 시작 인덱스 반환
(0은 그룹의 전체 패턴 (start(0) = start())
int start(String name)
: 매칭 문자열 중 해당 name을 지정한 그룹의 시작 인덱스 반환
int end()
: 매칭된 문자열의 마지막 인덱스 + 1 반환
int end(int group)
: 매칭 문자열 중 group번째 그룹의 마지막 문자열 이후(+1) 인덱스 반환
(0은 그룹의 전체 패턴을 의미 end(0) = end())
int end(String name)
: 매칭 문자열 중 해당 name을 지정한 그룹의 마지막 인덱스 + 1 반환
String group()
: 매칭된 문자열 반환
String group(int i)
: 매칭되는 문자열 중 i번째 그룹의 문자열 반환
(0은 그룹의 전체 패턴을 의미 group(0) = group())
String group(String name)
: 매칭된 문자열 중 해당 name을 지정한 그룹의 문자열 반환
int groupCount()
: 패턴 내에 그룹화한 개수를 반환
(패턴에 있는 괄호 개수)
boolean matches()
: 패턴에 전체 문자열이 일치한 경우 true를 반환
boolean find()
: 패턴이 일치하는 문자열이 있으면 true 반환
boolean find(int start)
: start 인덱스 이후부터 패턴에 일치하는 문자열을이 있으면 true 반환
String replaceAll(String replacement)
: 패턴과 일치하는 모든 문자열을 지정된 replacement로 변경



사용하기

1. 정규 표현식 생성

2. Pattern 클래스 생성

3. Matcher 메서드 생성

4. 패턴 판별 메서드

(1) Pattern.matches(regex, input)
(2) matcher.matches()

  1. Matcher 메서드
    fine()
    fine(int start)

  2. 매칭 위치 반환
    (1) start()
    -start(int i)
    (2) end()
    -end(int i)

  3. 그룹화
    (1) group()
    -group(int i)
    (2) ?<'이름'>



1. 정규 표현식 생성

  • String regex = 정규 표현식;
String regex = "^[a-zA-Z]$";
String input = "Test";

1. System.out.println(Pattern.matches(regex, input)); // false

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.mathcher(input);

2. System.out.println(matcher.matches()); // false

2. Pattern 클래스 생성

Pattern pattern = Pattern.compile(regex);

3. Matcher 메서드 생성

Matcher matcher = pattern.mathcher(input);



4. 패턴 판별 메서드

(1) Pattern.matches(regex, input)

(2) matcher.matches()

: 주어진 문자열이 패턴에 맞는지 판별하는 메서드


* Matcher 메서드

fine()

: 패턴이 일치하는 문자열이 존재하면 true

fine(int start)

: start 위치 이후부터 매칭 패턴 검색

Pattern pattern = Pattern.compile("([0-9]+)([SDT])([*#]?)");
Matcher matcher = pattern.matcher("1D2S#10S*);

while (matcher.fine()) {
	System.out.println(matcher.group());
}

// 1D
// 2S#
// 10S*

- 매칭 위치 반환

(1) start()

: 패턴이 일치하는 문자열의 시작 index

start(int i)

: i번째 그룹의 시작 문자열 index


(2) end()

: 패턴이 끝나는 문자열의 index + 1

end(int i)

: i번째 그룹의 종료 문자열 index + 1

while (matcher.find()) {
  System.out.println(matcher.group(1) + "/" + matcher.group(2) + "/" + matcher.group(3));
  System.out.println(matcher.start(1) + "/" + matcher.start(2) + "/" + matcher.start(3));
  System.out.println(matcher.end(1) + "/" + matcher.end(2) + "/" + matcher.end(3));
  System.out.println();
}

/* 출력
1/D/
0/1/2
1/2/2

2/S/#
2/3/4
3/4/5

10/S/*
5/7/8
7/8/9
*/

- 그룹화

(1) group()

: 매칭된 그룹 반환

group(int i)

: 매칭된 그룹 중 i번째 그룹 반환

(2) ?<'이름'>

: 그룹에 이름 붙이기

Pattern pattern = Pattern.compile("(?<a>[0-9]+)(?<b>[SDT])(?<c>[*#]?)");
Matcher matcher = pattern.matcher("1D2S#10S*");

while(matcher.find()){
  System.out.println(matcher.group("a"));
}
// 1
// 2
// 10


참고 블로그
https://girawhale.tistory.com/77
https://enterkey.tistory.com/353

https://m.blog.naver.com/elder815/220442548728
https://hhyeok1026.tistory.com/82

profile
비전공자 개발 일기

0개의 댓글