백엔드 다락방
[Java] - 정규표현식(RegExp) 본문
정규표현식(RegExp)
실무에서 잊을만하면 한 번씩 사용하는 정규표현식에 대해 정리하고자 작성하게 되었습니다. 정규표현식을 제대로 익히고 사용하는 것이 좋지만 정규표현식을 공부할 정도로 사용하는 빈도가 매우 낮다면 저는 ChatGPT를 사용하시는 것을 권장합니다. 설명만 잘하면 원하는 정규표현식을 뚝딱 만들어주는 우리의 갓피티...!
정규표현식 연습 사이트 : https://regexr.com/
RegExr: Learn, Build, & Test RegEx
RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp).
regexr.com
Groups and Ranges(그룹과 범위)
ㅇㅂㅈ
ㅂㅈㅇ
ㅂㅈㅇㅂㅈㅇㅂㅈㅇ
// ExecutorService + Future 사용 예시
ExecutorService exec = Executors.newFixedThreadPool(4);
Future<String> future = exec.submit(() -> {
simulate(); // 작업 수행
return "서버 응답 데이터";
});
String result = future.get(); // 블로킹: 호출 스레드가 여기서 멈춰 대기
// Future 작업이 완료 된 후 이후 로직 실행
Regular Expression | Description |
| | 또는 |
() | 그룹 |
[] | 문자셋, 괄호안의 문자 허용 |
[^] | 부정 문자셋, 괄호안의 문자 허용하지 않음 |
(?:) | 찾지만 기억하지는 않음 |
예시
- Hi
Hi
there, Nice to meet you. And Hello there and hi. - Hi | Hello
Hi
there, Nice to meet you. AndHello
there and hi. - (Hi | Hello)
Hi
there, Nice to meet you. AndHello
there and hi.
- Group 1 : Hi, Hello - (Hi | Hello) | (And)
Hi
there, Nice to meet you.And
Hello
there and hi.
- Group 1 : Hi, Hello
- Group 2 : And - gr(e | a)y
I lovegrey
(gray
) colar not a gry, graay and graaay.
- Group 1 : e, a - gr(?:e | a)y
I lovegrey
(gray
) colar not a gry, graay and graaay.
- Group으로 기억하지 않는다. - gr[ea]y
I lovegrey
(gray
) colar not a gry, graay and graaay. - gr[a-e]y
I lovegrey
(gray
) colar not a gry, graay and graaay. - [a-z0-9]
Hello3
- [^a-z0-9]
H
ello3
Quantifiers(수량)
Regular Expression | Description |
? | zero or one(0개나 1개) |
* | zero or more(0개나 1개이상) |
+ | one or more(1개이상) |
{n} | n번 반복 |
{min,} | 최소 min반복 |
{min,max} | 최소 min, 최대 max 반복 |
예시 - I love grey(gray) color not a gry, graay and graaay.
- gra?y
I love grey(gray
) color not agry
, graay and graaay. - gra*y
I love grey(gray
) color not agry
,graay
andgraaay
. - gra+y
I love grey(gray
) color not a gry,graay
andgraaay
. - gra{2}y
I love grey(gray) color not a gry,graay
and graaay. - gra{2,3}y
I love grey(gray) color not a gry,graay
andgraaay
.
Boundary-Type(단어경계)
Regular Expression | Description |
\b | 단어 경계 문자 |
\B | 단어 경계 문자가 아님 |
^ | 문장의 시작 (단어가 아닌 문장의 시작인 점을 주의) |
& | 문장의 끝 (단어가 아닌 문장의 끝인 점을 주의) |
예시 - Ya ya YaYaYa YaYaEa Ya
- \bYa
Ya
yaYa
YaYaYa
YaEaYa
- Ya\b
Ya
ya YaYaYa
YaYaEaYa
- \BYa
Ya ya YaYaYa
YaYa
Ea Ya - Ya\B
Ya yaYaYa
YaYaYa
Ea Ya - ^Ya
Ya
ya YaYaYa YaYaEa Ya - Ya&
Ya ya YaYaYa YaYaEaYa
- (\bYa)|(Ea\b)
Ya
yaYa
YaYaYa
YaEa
Ya
Character Classes(문자)
Regular Expression | Description |
\ | escape 문자 |
. | 어떤 글자(줄바꿈 문자 제외) |
\d | digit(숫자) |
\D | digit 이 아닌 문자 |
\w | word(문자) |
\W | word 가 아닌 문자 |
\s | space(공백) |
\S | space 가 아닌 문자 |
예시
- .
.
[]{}()^$|?*+ - \[]
.[]
{}()^$|?*+ - \d
gray012345
- \D
gray
012345