정규표현식 생성 모듈

고랭·2020년 4월 21일
0

솔루션 개발 과정에서 사용자 입력값을 받는 input 태그에는 여러가지 사양이 붙곤 합니다.

"설정명은 국문/영문/숫자/특수기호/공백 허용하면서, 백슬래시(\)와 언더바(_)는 제외해주세요"
"금액은 숫자와 쉼표(,)와 하이픈(-)만 허용해주세요"

이런 내용들을 처리하기 위해서는 다양한 event 처리와 내부에 값을 체크하는 정규표현식이 필요합니다.
이번 글에서는 정규표현식을 생성하는 모듈을 만들었던 것을 소개해볼까 합니다.

미리 만들어진 공통 코드가 있고, 개발자들이 이 코드를 사용하여 프로젝트를 개발하였더라도
사용자의 편의를 위해 조금씩 변동되는 사양들을 반영하기 위해
기존의 공통 모듈을 활용하여 아래와 같은 정규표현식 모듈을 만들어 보았습니다.
(※ 해당 모듈은 jquery를 포함하여야 동작합니다.)

- 기능

설정한 옵션에 정규표현식 맞추어 생성한다.
설정 가능한 옵션으로는 Flag, 포함/제외, 추가포함단어, 예외기호의 총 4가지 옵션이 있습니다.

- 사용법

1) 국문/영문/특수기호/공백과 숫자 0과 1을 허용, 백슬래시(\)와 언더바(_)는 제외를 체크하는 정규표현식

const oRegExp = REGEXP.getRegexp({
    checkType: ['KOR', 'ENG', 'SYMBOL', 'SPACE'], // 체크할 타입 (reverse에 따라 허용/금지 타입이 될 수 있음)
    flag: ['g'], // 정규표현식 flag
    reverse: true, // 허용/금지 설정 (true: checkType '외' / false: checkType '을')
    includeWord: ['0', '1'], // checkType에 추가적으로 포함할 키워드
    exceptionSymbol: ['\', '_'] // checkType이나 includeWord에 포함되었지만, 제외할 기호 배열
});

if (oRegExp['result'] === 'success') {
    console.log('정규표현식: ' + oRegExp['value']);
} else {
    console.log(oRegExp['messge']);
}

※ includeWord 추가한 뒤, exceptionSymbol을 제외하는 구조이므로 포함 설정에 있는 키워드 이더라도, 제외 설정에 포함된 경우에는 제외된다.

2) 국문/숫자를 허용하며, 하이픈(-)만 추가로 허용을 체크하는 정규표현식

REGEXP.getRegexp({
    checkType: ['KOR', 'NUMBER'],
    flag: ['g'],
    includeWord: ['-'],
});

if (oRegExp['result'] === 'success') {
    console.log('정규표현식: ' + oRegExp['value']);
} else {
    console.log(oRegExp['messge']);
}

- 코드 (regexp.js)

const REGEXP = (function () {
    const _oDefault = {
        KOR: 'ㄱ-ㅎ가-힣ㅏ-ㅣ',
        ENG: 'A-Za-z',
        NUMBER: '0-9',
        SPACE: '\\\s',
        SYMBOL: '\\\`\\\~!\\\@\\\#\\\$\\\%\\\^\\\&\\\*\\\(\\\)\\\-\\\_\\\=\\\+\\\?\\\(\\\)\\\{\\\}\\\[\\\]\\\\\\\|\\\:\\\;\\\'\\\"\\\,\\\<\\\.\\\>\\\/\\\?',
        CHECKTYPE: ['KOR', 'ENG', 'NUMBER', 'SPACE', 'SYMBOL'],
        FLAG: ['g', 'i', 'm', 's', 'x']
    };
    const _getReturn = function (sResult, sCode, mRegexp = '') {
        return {
            result: sResult,
            code: sCode,
            message: _getMessage(sCode),
            value: mRegexp
        }
    };
    const _getMessage = function (sCode) {
        const oMessage = {
            M00: 'Regexp making success',
            M01: 'Invalid checktype',
        };
        return oMessage[sCode];
    };
    const _initOption = function (oOption) {
        let {checkType, flag, reverse, includeWord, exceptionSymbol, ...others} = oOption;

        if (typeof checkType === 'undefined' || typeof checkType !== 'object' || checkType.length <= 0) {
            checkType = [];
        } else {
            $.each(checkType, function (iIndex, sCheckType) {
                if ($.inArray(sCheckType, _oDefault.CHECKTYPE) === -1) {
                    checkType.splice(iIndex, 1);
                }
            });
        }

        if (typeof flag === 'undefined' || typeof flag !== 'object' || flag.length <= 0) {
            flag = '';
        } else {
            flag = $.each(flag, function (iIndex, sFlag) {
                if ($.inArray(sFlag, _oDefault.FLAG) === -1) {
                    flag.splice(iIndex, 1);
                }
            }).join('');
        }

        if (typeof reverse === 'undefined' || $.inArray(reverse, [true, false]) === -1) reverse = true;
        if (typeof includeWord === 'undefined' || typeof includeWord !== 'object' || includeWord.length <= 0) includeWord = [];
        if (typeof exceptionSymbol === 'undefined' || typeof exceptionSymbol !== 'object' || exceptionSymbol.length <= 0) exceptionSymbol = [];

        return $.extend({
            checkType: checkType,
            flag: flag,
            reverse: reverse,
            includeWord: includeWord,
            exceptionSymbol: exceptionSymbol
        }, others);
    };

    return {
        getRegexp: function (oOption) {
            oOption = _initOption(oOption);

            if (oOption.checkType.length <= 0 && oOption.includeWord.length <= 0) return _getReturn('fail', 'M01');

            let sRegExp = '';
            $.each(oOption.checkType, function (iIndex, sCheckType) {
                sRegExp += _oDefault[sCheckType];
            });

            if (oOption.includeWord.length > 0) sRegExp += oOption.includeWord.join('');

            let sFrontWord = '', sBackWord = '';
            if (oOption.exceptionSymbol.length > 0) {
                $.each(oOption.exceptionSymbol, function (iIndex, sExclude) {
                    let iCurIndex = sRegExp.indexOf(sExclude);
                    if (iCurIndex !== -1) {
                        sFrontWord = sRegExp.substr(0, iCurIndex - 1);
                        sBackWord = sRegExp.substr(iCurIndex + 1, sRegExp.length);
                        sRegExp = sFrontWord + sBackWord;
                    }
                });
            }

            sRegExp = '[' + (oOption.reverse ? '^' : '') + sRegExp + ']';

            return _getReturn('success', 'M00', new RegExp(sRegExp, oOption.flag));
        }
    }
})();

- 마무리

매번 느끼는 거지만 코드는 직접 만들어 쓰는 것도 좋지만 이미 누군가는 만들어두었습니다.
이미 만들어둔 코드를 이해하고, 응용하여 원하는 기능에 적합하게 수정할 수 있는 개발자가 되기 위해 노력해보았습니다.

profile
만년신입

0개의 댓글