본문 바로가기

과거공부모음

정규 표현식(Regular Expression)

정규 표현식(Regular Expression)이란?

문자열 검색, 추출, 치환 등의 작업을 수행할 때 사용되는 패턴 매칭 기법이다.

정규 표현식은 특정한 규칙을 따르며 이 규칙에 따라 문자열의 구조와 일치하는 부분을

찾아내거나 다른 문자열로 대체할 수 있다.

프로그래밍 언어와 텍스트 편집기에서 광범위하게 사용되며 특히 텍스트 처리와 관련된 작업에

유용하게 사용된다.

정규 표현식 구성 요소

리터럴(Literals)

일반 문자, 그대로 일치하는 문자열을 찾습니다.

예) apple은 apple과 일치한다.

메타 문자(Meta characters)

특수한 의미를 가지고 있는 문자, 정규 표현식의 규칙을 정의하는 데 사용한다.

예) , * + ? ^ $ 등등

문자 클래스(Character classes)

대괄호 안에 있는 문자들 중 하나와 일치하는 문자를 찾는다.

예) [abc]는 a, b, c 중 하나와 일치한다.

그룹화(Grouping)

소괄호를 사용해 정규 표현식의 일부분을 그룹으로 묶어 처리할 수 있다.

대체(Alternation)

파이프를 사용해 여러 패턴 중 하나와 일치하는 문자열을 찾는다.

예) apple|orange는 apple 또는 orange와 일치한다.

앵커(Anchors)

문자열의 시작(^)이나 끝($)을 나타내는 메타 문자이다.

이스케이프(Escape)

역 슬래시를 사용하여 메타 문자를 리터럴로 사용하거나 특수 문자를 표현할 때 사용한다.

예) \d는 숫자와 일치한다. \.은 리터럴. 과 일치한다.

 

정규 표현식은 복잡한 패턴을 다룰 때 가독성이 떨어져 이해하기 어려울 수 있다.

따라서 필요한 기능만 사용하고 읽기 쉬운 정규 표현식을 작성하는 것이 중요하다.

정규 표현식은 어디에 사용할까?

이메일 주소 검증

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$

전화번호 검증

^\\+?[\\d\\s-]+\\(?[\\d\\s-]+\\)?[\\d\\s-]+$

날짜 형식 검증

^(19|20)\\d\\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$

URL 검증

^(https?:\\/\\/)?([\\da-z.-]+)\\.([a-z.]{2,6})([\\/\\w .-]*)*\\/?$

IP 주소 검증

^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

이 외 다양한 상황에서 정규 표현식을 활용할 수 있다.

node.js에서 정규 표현식을 어떻게 사용할 수 있을까?

node.js에서 정규 표현식을 사용하려면 javascript 내장 RegExp 객체와 관련 메서드를 활용하면

node.js에서 정규 표현식을 사용할 수 있다.

test 메서드

정규 표현식이 문자열에 있는지 확인한다.

const regex = /apple/;
const text = "I have an apple.";

if (regex.test(text)) {
  console.log("Match found!");
} else {
  console.log("No match found.");
}

match 메서드

정규 표현식과 일치하는 문자열을 찾는다.

const regex = /apple/g; // 'g' 플래그를 사용하여 전체 문자열에서 모든 일치 항목을 찾습니다.
const text = "I have an apple and another apple.";

const matches = text.match(regex);

if (matches) {
  console.log(`Found ${matches.length} matches:`, matches);
} else {
  console.log("No match found.");
}

replace 메서드

정규 표현식과 일치하는 부분을 다른 문자열로 치환한다.

const regex = /apple/g;
const text = "I have an apple and another apple.";

const newText = text.replace(regex, "orange");

console.log("Replaced text:", newText);

split 메서드

정규 표현식을 기준으로 문자열을 나눈다.

const regex = /[,.]+/; // 쉼표와 마침표를 기준으로 문자열을 나눕니다.
const text = "I have, an apple. And another, apple.";

const parts = text.split(regex);

console.log("Splitted parts:", parts);

exec 메서드

정규 표현식과 일치하는 문자열과 그룹 정보를 찾는다.

const regex = /(apple|orange)/g;
const text = "I have an apple, an orange, and another apple.";

let match;
while ((match = regex.exec(text)) !== null) {
  console.log(`Match found at index ${match.index}:`, match[0]);
}

 

참고 자료

 

Regular expressions - JavaScript | MDN

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replac

developer.mozilla.org

 

'과거공부모음' 카테고리의 다른 글

MySQL 스토리지 엔진  (0) 2023.05.22
웹 서버와 웹 애플리케이션 서버  (0) 2023.04.26
클라우드 컴퓨팅  (0) 2023.04.24
멀티스레딩과 멀티프로세싱  (0) 2023.04.24
테스트(Testing)  (0) 2023.04.21