블로그

[JAVA] Regular Expression (정규 표현식) 본문

개발자 준비과정/JAVA

[JAVA] Regular Expression (정규 표현식)

하늘바람a 2024. 3. 15. 14:38

프로그래밍에서 문자열을 다룰 때, 문자열의 일정한 패턴을 표현하는 일종의 형식 언어를 말한다. 정규식이라고도 부르며, 보통 RegEx 혹은 RegExp라 많이 쓴다.

 

이메일이나 전화번호처럼 사용자가 입력한 값이 정해진 형식으로 구성되어 있는지 검증할 때,

일정한 규칙을 가진 텍스트 문자열을 사용할 때에 정규 표현식을 사용한다.

 

정규 표현식은 사용되는 언어마다 문법이 조금씩 다를 수도 있다. 정규표현식을 구현한 엔진들끼리도 조금씩 다른 경우가 있으므로 자신이 익숙한 환경이 아니라면 미리 확인을 해보는 것이 중요하다. 

 

정규 표현식 작성 방법

^ (caret) 시작
$
 

 

코드로 실습해보며 알아보자

// 한 문자
System.out.println("aa".matches("a")); // false
System.out.println("ab".matches("ab")); // true
System.out.println("ab".matches("ba")); // false

// 대소문자 구분함
System.out.println("a".matches("a")); // true
System.out.println("a".matches("A")); // false

 

// 문자집합
System.out.println("c".matches("[abc]")); // true
System.out.println("A".matches("[abc]")); // false
System.out.println("abc".matches("[abc]")); // false //abc 중 하나여야 함

String p1 = "[abc][abc][abc]";
System.out.println("bac".matches(p1)); // true
System.out.println("aaa".matches(p1)); // true

String p2 = "[a-z]";
System.out.println("a".matches(p2)); // true
System.out.println("D".matches(p2)); // false

String p3 = "[a-zA-Z]"; // [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ] 소문자, 대문자 모두가능
System.out.println("s".matches(p3)); // true
System.out.println("S".matches(p3)); // true

String p4 = "[a-zA-Z0-9]"; //영문대소문자와 숫자
String p5 = "[가-힣]"; // 한글 한글자

String p6 = "[^abc]"; // a, b, c 외
System.out.println("a".matches(p6)); // false
System.out.println("8".matches(p6)); // true
System.out.println("xyz".matches(p6)); // false

 

// [0-9] : \d
// whitespace : \s
// word character [a-zA-Z0-9_] : \w
// 모든 문자 : .

// [0-9] : \d
System.out.println("0".matches(p1)); // true
System.out.println("012".matches(p1));  // false

// whitespace : \s
System.out.println(" ".matches("\\s")); // true

// word character [a-zA-Z0-9_] : \w
System.out.println("_".matches("\\w")); // true
System.out.println("$".matches("\\w")); // false

// 모든 문자 : .
System.out.println("a".matches(".")); // true
System.out.println(" ".matches(".")); // true
System.out.println("$".matches(".")); // true
System.out.println("".matches(".")); // false

 

// 수량자

// {n} : 정확히 n번
String p1 = "\\d{3}";
String p2 = "010-\\d{4}-\\d{4}";

// {n,m} : n~m번
String p3 = "[가-힣]{2,4}";

// {n,} : n번 이상
String p4 = "[가-힣]{2,}";
String p5 = "[a-zA-Z가-힣]{1,}"; // 영문대소문자와 한글 한글자 이상

// + : {1,} : 1번 이상
String p7 = "\\w+";

// * : {0,} : 0번 이상
String p8 = "\\w*";

// ? : {0,1} : 한번 또는 없음
String p6 = "010-{0,1}\\d{4}-{0,1}\\d{4}";

 

 

다음은 자바 API에 기재된 정규표현식이다.

정확한 정규표현식을 알고싶을때 이곳을 보면 된다.

https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/regex/Pattern.html#sum

 

Pattern (Java SE 21 & JDK 21)

All Implemented Interfaces: Serializable A compiled representation of a regular expression. A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher objec

docs.oracle.com

 

 

정규표현식을 확인하는 데 유용한 사이트도 같이 소개해본다.

https://regex101.com/

 

regex101: build, test, and debug regex

Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java, C#/.NET, Rust.

regex101.com

 

'개발자 준비과정 > JAVA' 카테고리의 다른 글

[JAVA] 스트림 기초  (0) 2024.03.21
[JAVA] 제네릭(Generic)  (0) 2024.03.15
[JAVA] Object 클래스, 포장 클래스(Wrapper class)  (1) 2024.03.14
[JAVA] 람다식  (0) 2024.03.13
[JAVA] 중첩 클래스, 익명 클래스  (0) 2024.03.12