RegExp

RegExp 생성자는 패턴을 사용한 텍스트 판별에 사용할 정규 표현식 객체를 생성합니다.

정규 표현식에 대한 소개는 JavaScript 안내서의 정규 표현식을 참고하세요.

구문

정규 표현식 리터럴, 생성자, 팩토리 표기법이 가능합니다.

/pattern/flags
new RegExp(pattern[, flags])
RegExp(pattern[, flags])

매개변수

pattern
정규 표현식을 나타내는 텍스트, 또는 ES5 이후에서는 다른 RegExp 객체 혹은 리터럴(리터럴의 경우 생성자 표기법에서만 가능). 패턴은 특수 문자를 포함할 수 있어, 일반적인 문자열 리터럴보다 더 넓은 범위의 값을 판별할 수 있습니다.
flags

(명시되어 있을 경우) 추가할 플래그를 담은 문자열. 기존의 객체를 패턴으로 입력한 경우 그 객체의 플래그가 flags 문자열로 바뀌며, 추가로 lastIndex가 0으로 초기화됩니다 (ES2015 이후). 기존의 정규 표현식 객체를 패턴으로 입력하고 flags를 명시하지 않았을 경우 기존 객체의 플래그(와 lastIndex 값)이 복제됩니다.

flags는 다음 문자를 조합하여 명시할 수 있습니다.

g
전체 판별. 처음 일치에서 중단하지 않고, 문자열 전체를 판별합니다.
i
대소문자 무시. u 플래그까지 활성화된 경우, 유니코드 대소문자 폴딩을 사용합니다.
m
여러 줄. 시작 혹은 끝 문자(^과 $)가 여러 줄에 적용되도록 합니다. 즉, 전체 입력 문자열의 맨 처음과 맨 끝뿐만이 아니라 (\n이나 \r로 구분되는) 모든 줄의 처음과 끝에 적용됩니다.
s
"dotAll". . 문자가 줄바꿈을 포함한 모든 문자에 일치합니다.
u
유니코드. 패턴을 유니코드 코드 포인트 열로 처리합니다. (Binary strings 참조)
y
sticky. 이 정규 표현식의 lastIndex 속성에 명시된 인덱스에서만 판별하고, 이전/이후 인덱스에서 판별을 시도하지 않습니다.

설명

RegExp 객체를 만들 때는 리터럴 표기와 생성자의 2가지 방법을 사용할 수 있습니다. 리터럴 표기의 매개변수는 양쪽을 슬래시(/)로 감싸고 따옴표를 사용하지 않는 반면, 생성자 함수의 경우 슬래시 대신 따옴표를 사용합니다.

아래의 코드는 모두 동일한 정규 표현식을 생성합니다.

/ab+c/i;
new RegExp(/ab+c/, 'i'); // 리터럴 표기
new RegExp('ab+c', 'i'); // 생성자

리터럴 방식의 경우 표현식을 평가할 때 정규 표현식을 컴파일된 형태로 제공합니다. 정규 표현식의 패턴을 바꾸지 않을 경우 리터럴 표기를 사용하는 것이 좋습니다. 예를 들어, 정규 표현식을 리터럴 표기로 생성하고 반복문 안에서 사용할 경우 매번 반복할 때마다 정규 표현식이 다시 컴파일되지 않습니다.

new RegExp('ab+c')와 같은 생성자 방식의 경우 정규 표현식을 실행 시 컴파일합니다. 정규 표현식의 패턴을 자주 바꾸거나 사용자 입력 등 외부에서 패턴을 받아올 경우 생성자 함수를 사용합니다.

ECMAScript 6부터는 new RegExp(/ab+c/, 'i')처럼 첫 인자가 RegExp이고 flags 인자가 있을 때에도 TypeError ("can't supply flags when constructing one RegExp from another")를 발생하지 않고 새로운 RegExp를 생성합니다.

생성자 함수를 사용할 경우 보통의 문자열 탈출 규칙[특수문자를 문자열에 사용할 때 앞에 역슬래시(\)를 붙이는 것]을 반드시 준수해야 합니다. 예를 들면 다음 코드는 동일한 정규 표현식을 생성합니다.

var re = /\w+/;
var re = new RegExp('\\w+');

속성

RegExp.prototype
모든 RegExp 객체에 속성을 추가할 수 있습니다.
RegExp.length
RegExp.length의 값은 2입니다.
get RegExp[@@species]
파생 객체를 생성할 때 사용한 생성자 함수.
RegExp.lastIndex
다음 판별을 시작할 인덱스.

메서드

전역 RegExp 객체 자체에는 메서드가 없지만, 프로토타입 체인으로부터 일부 메서드를 상속받습니다.

RegExp 프로토타입 객체와 인스턴스

속성

See also deprecated RegExp properties.

Note that several of the RegExp properties have both long and short (Perl-like) names. Both names always refer to the same value. Perl is the programming language from which JavaScript modeled its regular expressions.

RegExp.prototype.constructor
Specifies the function that creates an object's prototype.
RegExp.prototype.flags
A string that contains the flags of the RegExp object.
RegExp.prototype.dotAll
Whether . matches newlines or not.
RegExp.prototype.global
Whether to test the regular expression against all possible matches in a string, or only against the first.
RegExp.prototype.ignoreCase
Whether to ignore case while attempting a match in a string.
RegExp.prototype.multiline
Whether or not to search in strings across multiple lines.
RegExp.prototype.source
The text of the pattern.
RegExp.prototype.sticky
Whether or not the search is sticky.
RegExp.prototype.unicode
Whether or not Unicode features are enabled.

메서드

RegExp.prototype.compile()
(Re-)compiles a regular expression during execution of a script.
RegExp.prototype.exec()
Executes a search for a match in its string parameter.
RegExp.prototype.test()
Tests for a match in its string parameter.
RegExp.prototype[@@match]()
Performs match to given string and returns match result.
RegExp.prototype[@@matchAll]()
Returns all matches of the regular expression against a string.
RegExp.prototype[@@replace]()
Replaces matches in given string with new substring.
RegExp.prototype[@@search]()
Searches the match in given string and returns the index the pattern found in the string.
RegExp.prototype[@@split]()
Splits given string into an array by separating the string into substring.
RegExp.prototype.toSource()
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.prototype.toSource() method.
RegExp.prototype.toString()
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.

예제

정규 표현식을 사용해서 데이터 형식 바꾸기

다음 스크립트에서는 String 객체의 replace() 메서드를 사용하여 이름 성씨 형태의 이름을 판별하고 성씨, 이름 형태로 반환합니다. 바꿀 문자열에서는 $1과 $2를 사용하여 정규 표현식 패턴의 각 괄호에 포획된 결과를 받아옵니다.

var re = /(\w+)\s(\w+)/;
var str = 'John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);

실행 결과는 "Smith, John"입니다.

정규 표현식을 사용해서 여러 가지 줄바꿈 문자가 있는 문자열 나누기

기본적으로 사용하는 줄바꿈 문자는 플랫폼(유닉스, 윈도우 등)마다 다릅니다. 아래 스크립트는 모든 플랫폼의 줄바꿈을 인식합니다.

var text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end';
var lines = text.split(/\r\n|\r|\n/);
console.log(lines); // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]

이때 정규 표현식의 패턴 순서가 바뀌면 정상적으로 동작하지 않습니다.

여러 줄에서 정규 표현식 사용하기

var s = 'Please yes\nmake my day!';
s.match(/yes.*day/);
// Returns null
s.match(/yes[^]*day/);
// Returns 'yes\nmake my day'

sticky 플래그와 함께 사용하기

sticky 플래그를 사용하면 해당 정규표현식이 sticky 판별, 즉 RegExp.prototype.lastIndex에서 시작하는 일치만 확인하도록 할 수 있습니다.

var str = '#foo#';
var regex = /foo/y;

regex.lastIndex = 1;
regex.test(str); // true
regex.lastIndex = 5;
regex.test(str); // false (lastIndex가 판별에 영향을 미침)
regex.lastIndex; // 0 (일치하지 않으면 초기화)

정규 표현식과 유니코드 문자

위에서 언급했듯이 \w\W는 "a"부터 "z"까지, "A"부터 "Z"까지, "0"부터 "9"까지와 "_" 등의 ASCII 문자만 일치합니다. 러시아어나 히브리어와 같은 다른 언어의 문자까지 일치하려면 \uhhhh(이때 hhhh는 해당 문자의 16진법 유니코드 값) 문법을 사용하세요. 아래 예제에서는 문자열에서 유니코드 문자를 추출합니다.

var text = 'Образец text на русском языке';
var regex = /[\u0400-\u04FF]+/g;

var match = regex.exec(text);
console.log(match[0]);        // 'Образец' 출력
console.log(regex.lastIndex); // '7' 출력

var match2 = regex.exec(text);
console.log(match2[0]);       // 'на' 출력 ['text'가 아님]
console.log(regex.lastIndex); // '15' 출력

// 계속

유니코드 속성 탈출 기능을 사용해 \p{scx=Cyrl}과 같은 간단한 문법으로 이러한 문제를 해결할 수 있습니다. Regexp-unicode-block과 같은 외부 사이트에서 여러 문자의 유니코드 범위를 확인할 수도 있습니다.

URL에서 서브도메인 추출하기

var url = 'http://xxx.domain.com';
console.log(/[^.]+/.exec(url)[0].substr(7)); // 'xxx' 출력

명세

명세 상태 비고
ECMAScript 3rd Edition (ECMA-262) Standard 초기 정의. JavaScript 1.1에 구현됨.
ECMAScript 5.1 (ECMA-262)
The definition of 'RegExp' in that specification.
Standard
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'RegExp' in that specification.
Standard RegExp 생성자의 첫 인자가 RegExp이고 두 번째 인자가 있을 때도 오류를 발생하지 않게 됨.
ECMAScript Latest Draft (ECMA-262)
The definition of 'RegExp' in that specification.
Draft

브라우저 호환성

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
RegExpChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
compile
Deprecated
Chrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
dotAllChrome Full support 62Edge No support NoFirefox No support NoIE No support NoOpera Full support 49Safari Full support 12WebView Android Full support 62Chrome Android Full support 62Firefox Android No support NoOpera Android Full support 46Safari iOS Full support 12Samsung Internet Android Full support Yesnodejs Full support 8.10.0
Full support 8.10.0
Full support 8.3.0
Disabled
Disabled From version 8.3.0: this feature is behind the --harmony runtime flag.
execChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
flagsChrome Full support YesEdge Full support Yes
Disabled
Full support Yes
Disabled
Disabled This feature is behind the Experimental JavaScript Features preference.
Firefox Full support 37IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 37Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 6.0.0
globalChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
ignoreCaseChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
RegExp.input ($_)
Non-standard
Chrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
lastIndexChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
RegExp.lastMatch ($&)
Non-standard
Chrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
RegExp.lastParen ($+)
Non-standard
Chrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
RegExp.leftContext ($`)
Non-standard
Chrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
lookbehind assertions ((?<= ) and (?<! ))Chrome Full support 62Edge No support NoFirefox No support No
Notes
No support No
Notes
Notes See bug 1225665.
IE No support NoOpera Full support 49Safari No support NoWebView Android Full support 62Chrome Android Full support 62Firefox Android No support No
Notes
No support No
Notes
Notes See bug 1225665.
Opera Android Full support 46Safari iOS No support NoSamsung Internet Android Full support Yesnodejs Full support 8.10.0
multilineChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
RegExp.$1-$9
Non-standard
Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Named capture groups
Non-standard
Chrome Full support 64Edge No support NoFirefox No support NoIE No support NoOpera Full support 51Safari Full support 11.1WebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS Full support 11.3Samsung Internet Android Full support 9.0nodejs Full support 10.0.0
Full support 10.0.0
Full support 8.3.0
Disabled
Disabled From version 8.3.0: this feature is behind the --harmony runtime flag.
Unicode property escapes (\p{...})Chrome Full support 64Edge ? Firefox No support NoIE ? Opera Full support 51Safari ? WebView Android Full support 64Chrome Android Full support 64Firefox Android No support NoOpera Android Full support 47Safari iOS ? Samsung Internet Android Full support Yesnodejs Full support 10.0.0
Full support 10.0.0
Full support 8.3.0
Disabled
Disabled From version 8.3.0: this feature is behind the --harmony runtime flag.
prototypeChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
RegExp.rightContext ($')
Non-standard
Chrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
sourceChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
stickyChrome Full support 49Edge Full support 13Firefox Full support 3IE No support NoOpera Full support 36Safari Full support 10WebView Android Full support 49Chrome Android Full support 49Firefox Android Full support 4Opera Android Full support 36Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support Yes
testChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
toSource
Non-standard
Chrome No support NoEdge No support NoFirefox Full support 1IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No
toStringChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
unicodeChrome Full support 50Edge Full support 12
Notes
Full support 12
Notes
Notes Case folding is implemented in version 13
Firefox Full support 46IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support YesChrome Android Full support 50Firefox Android Full support 46Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support Yes
@@matchChrome Full support YesEdge Full support YesFirefox Full support 49IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 49Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 6.0.0
@@matchAllChrome Full support 73Edge No support NoFirefox Full support 67IE No support NoOpera Full support 60Safari No support NoWebView Android Full support 73Chrome Android Full support 73Firefox Android Full support 67Opera Android Full support YesSafari iOS No support NoSamsung Internet Android Full support Yesnodejs Full support 12.0.0
@@replaceChrome Full support YesEdge Full support YesFirefox Full support 49IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 49Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 6.0.0
@@searchChrome Full support YesEdge Full support YesFirefox Full support 49IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 49Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 6.0.0
@@speciesChrome Full support YesEdge Full support YesFirefox Full support 49IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 49Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 6.5.0
Full support 6.5.0
Full support 6.0.0
Disabled
Disabled From version 6.0.0: this feature is behind the --harmony runtime flag.
@@splitChrome Full support YesEdge Full support YesFirefox Full support 49IE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 49Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support 6.0.0

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

같이 보기