JavaScript

[JavaScript] 정규식

댕주 2024. 11. 16. 21:02

정규식(Regular Expressions)문자열 패턴을 정의하는 도구로, 문자열 검색, 매칭, 추출, 치환 등 다양한 작업에 활용된다.

 

1. 정규식의 기본 구조

1-1. 정규식 리터럴

슬래시( / )로 감싸서 정의한다

const regex = /abc/

 

1-2. RegExp 객체

new RegExp() 를 사용하여 동적으로 정규식을 생성한다

const regex = new RegExp('abc'); // 'abc'라는 문자열을 찾는 정규식

 

2. 정규식의 주요 기능

2-1. 매칭 (검색)

  • 정규식을 사용하여 문자열에서 특정 패턴을 검색한다
const regex = /hello/;
const str = 'hello world'
console.log(regex.test(str)); // true

 

2-2. 문자열 추출

  • 정규식을 사용하여 문자열에서 원하는 부분을 추출한다
const regex = /\d+/;
const str = 'TEST 123';
console.log(str.match(regex)); // ['123']

 

2-3. 치환 (변경)

  • 정규식을 사용하여 문자열의 특정 부분을 치환할 수 있다
const regex = /world/;
const str = 'hello world';
console.log(str.replace(regex, 'JavaScript')); // 'hello JavaScript'

 

3. 정규식의 구성 요소

  • 정규식은 특정 패턴을 정의하기 위해 다양한 메타문자와 플래그를 사용한다

3-1. 메타문자

메타문자 의미 예제
\d 숫자 (0-9) /\d+/ - 숫자 검색
\w 단어 문자 (알파벳, 숫자, _) /\w+/ - 단어 검색
\s 공백 문자 /\s+/ - 공백 검색
. 임의의 문자 (줄바꿈 제외) /a.b/ - a+b 매칭
^ 문자열의 시작 /^hello/ - 시작 매칭
$ 문자열의 끝 /world$/ - 끝 매칭
* 0개 이상 /a*/ - aaa, a
+ 1개 이상 /a+/ - aaa, a
? 0개 또는 1개 /colou?r/ - color, colour
{n,m} 최소 n 개, 최대 m 개 /\d{2,4}/ - 2~4자리 숫자

 

3-2. 플래그

플래그 의미 예제
g 전역 검색 /abc/g
i 대소문자 무시 /abc/i
m 여러 줄 검색 /^abc/m
s 줄바꿈 문자 포함 (. 확장) /a.b/s
u 유니코드 처리 /\u{61}/u (a)

 

4. 자주 사용하는 정규식 패턴

4-1. 이메일 검증

const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(regex.test("example@example.com")); // true

 

4-2. 전화번호 형식

const regex = /^\d{3}-\d{3,4}-\d{4}$/;
console.log(regex.test("010-1234-5678")); // true

 

4-3. 비밀번호 조건 (영문, 숫자 포함 8~16자)

const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/;
console.log(regex.test("password1")); // true

 

4-4. 소수점 숫자 (1~2자리 소수 허용)

const regex = /^\d+(\.\d{1,2})?$/;
console.log(regex.test("123.45")); // true
console.log(regex.test("123.456")); // false

 

5. 정규식 작성 시 주의사항

5-1. 공백 자체는 문자로 인식된다

const regex = /hello world/; // 'hello'와 'world' 사이에 정확히 한 칸의 공백이 있어야 함
console.log(regex.test("hello world")); // true
console.log(regex.test("helloworld"));  // false
console.log(regex.test("hello  world")); // false (공백 두 칸)

 

5-2. 공백을 명시적으로 처리

  • 공백이 0개 이상일 수 있으면 \s* 를 사용한다
  • 공백이 1개 이상일 수 있으면 \s+ 를 사용한다
  • 공백이 없어야 하면 정규식에 공백을 포함하지 않아야 한다

 

5-3. 예상치 못한 공백 문제 방지하기

(1) 문자열 앞뒤 공백 제거

  • 확인하려는 문자열에서 불필요한 공백이 있을 수 있으므로, 정규식을 적용하기 전에 .trim() 을 사용하여 공백을 제거한다
const userInput = "  hello world  ";
const regex = /hello world/;
console.log(regex.test(userInput)); // false
console.log(regex.test(userInput.trim())); // true

 

(2) 여러 공백을 하나로 변환

const userInput = "hello    world";
const normalizedInput = userInput.replace(/\s+/g, " "); // 여러 공백을 한 칸으로
console.log(normalizedInput); // "hello world"

 

5-4. 공백과 텍스트 혼합 처리

  • 공백과 텍스트가 섞여있는 입력을 정규식으로 처리할 때는 유연한 패턴을 사용하는 것이 중요하다
  • 예시: 여러 줄 텍스트에서 공백과 라인 구분하기
const multilineText = `hello    
world`;

const regex = /hello\s+world/; // 줄바꿈 포함 공백 처리
console.log(regex.test(multilineText)); // true

 

5-5. 공백 관련 자주 쓰는 정규식 패턴

  • 선두/후미 공백 제거: /^\s+|\s+$/g
  • 연속된 공백을 하나로 축소: /\s+/g
  • 모든 공백 제거: /\s/g

 

6. 정규식 디버깅 도구

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

https://regexr.com/

 

RegExr: Learn, Build, & Test RegEx

RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp).

regexr.com