자유로이

쉽게 알아가는 정규표현식 사용법 예제(자바,자바스크립트) 본문

IT/프로그래밍

쉽게 알아가는 정규표현식 사용법 예제(자바,자바스크립트)

wooyaa 2020. 8. 28. 11:27

전에 배웠던 정규표현식을 JAVA와 javascript로 사용하는 법을 알아보도록 하겠습니다.

 

자바에서 정규표현식을 사용하려면 Pattern 클래스Matcher 클래스를 이용합니다.

소스예제(자바)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public static void main(String[] args) {
    String strTarget = "Lorem Ipsum is simply dummy text of the printing and"
                         + "typesetting industry. 01012345678 Lorem Ipsum has been "
                         + "the industry's standard dummy text ever since the 1500s,"
                         + " 02-123-4567 when an unknown printer took a galley of type "
                         + "and scrambled it to make a type specimen book.010 1234 5678.";
     //정규식 패턴 설정   
     Pattern pattern = Pattern.compile("\\d{2,3}[- ]?\\d{3,4}[- ]?\\d{4}");

     Matcher matcher = pattern.matcher(strTarget);
     //패턴과 일치할경우 true를 반환하고 일치한것에 접근
     while(matcher.find()){
            System.out.println(matcher.group());
     }
}

 

Pattern pattern = Pattern.compile("\\d{2,3}[- ]?\\d{3,4}[- ]?\\d{4}");

pattern에 정규표현식으로 패턴을 만들고

(주의점은 \를 \\이렇게 두번써줘야 인식한다는 점입니다.

자바에서는 escape 때문에 한번만 적을 경우 역슬래시를 사용하기때문에 역슬래시 \를 두 번 적어야 합니다.)

Matcher matcher = pattern.matcher(strTarget);

matcher에 패턴에 매치시킬 문자열을 넣는것을 알수 있습니다.

 while(matcher.find())

반복문에 matcher.find()를 이용하여 패턴과 매치되는 것들을(패턴과 일치하면 true)

출력하는것을 볼수있습니다.

 

실행결과

자바에서 정규표현식을 사용하법을 알아보았습니다.

 

그럼 자바스크립트에서 사용하는 방법도 알아보겠습니다.

 

Javascript로 정규표현식을 다룰 때에는 String class의 match 함수를 이용합니다.

소스예제(자바스크립트)

var strTarget = "Lorem Ipsum is simply dummy text of the printing and"
                + "typesetting industry. 01012345678 Lorem Ipsum has been "
                + "the industry's standard dummy text ever since the 1500s,"
                + " 02-123-4567 when an unknown printer took a galley of type "
                + "and scrambled it to make a type specimen book.010 1234 5678.";

//패턴설정
var regexPattern = /\d{2,3}[- ]?\d{3,4}[- ]?\d{4}/g;
//패턴에 맞는 것들을 인식
console.log(strTarget.match(regexPattern));

var regexPattern = /\d{2,3}[- ]?\d{3,4}[- ]?\d{4}/g;

패턴을 생성해줍니다.

(패턴 처음과 끝에 /를 감싸줍니다.)

 

console.log(strTarget.match(regexPattern));

문자열에 .match(패턴)을 이용하여 일치하는것들을 출력합니다.

 

실행결과

패턴과 일치하는것들을 담은값을 출력하는것을 알수있습니다.

 

이렇게 자바와 자바스크립트에서 정규표현식을 사용하는법을 알아보았습니다.

 

도움이 되셨나요? :)

Comments