Skip to main content

Java: String.split() 정규식 예제 모음

✅ 기본 문법

String[] result = 문자열.split("정규표현식");

split()은 인자로 정규표현식(String regex) 을 받기 때문에, 메타 문자(예: . | *)는 반드시 이스케이프 해야 한다.


1. 공백 기준 분할

1.1 공백 하나

String s = "hello world";
String[] arr = s.split(" ");

1.2 공백 여러 개 (1개 이상)

String s = "hello   world  java";
String[] arr = s.split("\\s+");  // \\s = 공백 문자, +는 1개 이상

1.3 탭 또는 공백

String s = "a\tb c";
String[] arr = s.split("[ \t]+");

2. 콤마(,) 기준 분할

String s = "apple,banana,grape";
String[] arr = s.split(",");

2.1 콤마 + 공백 제거 (CSV 정리)

String s = "apple, banana,  grape";
String[] arr = s.split(",\\s*");  // , 뒤 공백 무시

3. 특수 문자 기준 분할

정규표현식에서 특수 문자는 반드시 이스케이프(\) 필요!

문자

정규표현식에서 의미

split에 쓰는 방식

.

모든 문자

"\\."

`

`

OR (또는)

*

반복자

"\\*"

(

)

[

]

그룹 지정

"\\(", "\\["

3.1 마침표(.) 기준

String s = "www.example.com";
String[] arr = s.split("\\.");

3.2 파이프(|) 기준

String s = "red|green|blue";
String[] arr = s.split("\\|");

4. 숫자/문자 기준 분할

4.1 숫자만 기준으로 나누기

String s = "abc123def456ghi";
String[] arr = s.split("\\d+");  // 숫자(1개 이상) 기준 나눔

4.2 문자 기준 나누기

String s = "123abc456def";
String[] arr = s.split("[a-zA-Z]+");  // 알파벳 기준 나눔

5. 복수 구분자 분리

5.1 콤마(,) 또는 세미콜론(;) 또는 공백

String s = "apple,banana;grape orange";
String[] arr = s.split("[,; ]");

5.2 AND/OR 조건 키워드 분리

String s = "red and blue or green";
String[] arr = s.split("\\s+(and|or)\\s+");  // 공백 포함한 and/or 기준

6. 문장 끝 단위 분리 (구두점)

String s = "Hi. I am John! Nice to meet you?";
String[] arr = s.split("[.!?]\\s*");  // . ! ? 뒤 공백까지 포함

7. 빈 문자열 처리

String s = "a,,b,c";
String[] arr = s.split(",", -1);  // -1 옵션으로 빈 항목도 유지
System.out.println(Arrays.toString(arr));
// 출력: [a, , b, c]

🧾 보너스: 정규표현식 요약표

패턴

의미

예시

\\s

공백 문자 (스페이스, 탭 등)

"\\s+"

→ 연속된 공백

\\d

숫자 (0~9)

"\\d+"

→ 숫자 1개 이상

\\w

문자/숫자/밑줄

"\\w+"

.

아무 문자 한 개

"a.b"

→ "acb", "a1b" 가능

[abc]

a 또는 b 또는 c

"a[bc]d"

→ "abd", "acd"

[^abc]

a,b,c 제외한 문자

"[^0-9]"

→ 숫자 제외

+

앞의 패턴 1번 이상 반복

"\\s+"

*

0번 이상 반복

"a*"

`

`

OR


✅ 결론

  • split()정규표현식 기반의 유연한 문자열 분리가 가능하다.
  • 단순 입력에는 StringTokenizer, 복잡한 기준 분리에는 split()이 적합.
  • 특수문자 분리 시 반드시 이스케이프(\\) 를 주의할 것!