RegExp 생성자는 패턴을 사용한 텍스트 판별에 사용할 정규 표현식 객체를 생성합니다.
정규 표현식에 대한 소개는 JavaScript 안내서의 정규 표현식을 참고하세요.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
구문
정규 표현식 리터럴, 생성자, 팩토리 표기법이 가능합니다.
/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.lengthRegExp.length의 값은 2입니다.get RegExp[@@species]- 파생 객체를 생성할 때 사용한 생성자 함수.
RegExp.lastIndex- 다음 판별을 시작할 인덱스.
메서드
전역 RegExp 객체 자체에는 메서드가 없지만, 프로토타입 체인으로부터 일부 메서드를 상속받습니다.
RegExp 프로토타입 객체와 인스턴스
속성
RegExp.prototype- Allows the addition of properties to all objects.
RegExp.length- The value of
RegExp.lengthis2. get RegExp[@@species]- The constructor function that is used to create derived objects.
RegExp.lastIndex- The index at which to start the next match.
메서드
The global RegExp object has no methods of its own. However, it does inherit some methods through the prototype chain.
예제
정규 표현식을 사용해서 데이터 형식 바꾸기
다음 스크립트에서는 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 (ECMA-262) The definition of 'RegExp' in that specification. |
Living Standard |
브라우저 호환성
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RegExp | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
RegExp() constructor | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
compile | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 6 | Safari Full support 3.1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 2 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
dotAll | Chrome Full support 62 | Edge Full support 79 | Firefox No support No | IE No support No | Opera Full support 49 | Safari Full support 12 | WebView Android Full support 62 | Chrome Android Full support 62 | Firefox Android No support No | Opera Android Full support 46 | Safari iOS Full support 12 | Samsung Internet Android Full support 8.0 | nodejs
Full support
8.10.0
|
exec | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
flags | Chrome Full support 49 | Edge Full support 79 | Firefox Full support 37 | IE No support No | Opera Full support 39 | Safari Full support 9 | WebView Android Full support 49 | Chrome Android Full support 49 | Firefox Android Full support 37 | Opera Android Full support 41 | Safari iOS Full support 9 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
global | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
ignoreCase | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
RegExp.input ($_) | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 15 | Safari Full support 3 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 14 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
lastIndex | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
RegExp.lastMatch ($&) | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 10.5 | Safari Full support 3 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 11 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
RegExp.lastParen ($+) | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 10.5 | Safari Full support 3 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 11 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
RegExp.leftContext ($`) | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 8 | Safari Full support 3 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
lookbehind assertions ((?<= ) and (?<! )) | Chrome Full support 62 | Edge Full support 79 | Firefox
No support
No
| IE No support No | Opera Full support 49 | Safari No support No | WebView Android Full support 62 | Chrome Android Full support 62 | Firefox Android
No support
No
| Opera Android Full support 46 | Safari iOS No support No | Samsung Internet Android Full support 8.0 | nodejs Full support 8.10.0 |
multiline | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
RegExp.$1-$9 | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
| Named capture groups | Chrome Full support 64 | Edge Full support 79 | Firefox No support No | IE No support No | Opera Full support 51 | Safari Full support 11.1 | WebView Android Full support 64 | Chrome Android Full support 64 | Firefox Android No support No | Opera Android Full support 47 | Safari iOS Full support 11.3 | Samsung Internet Android Full support 9.0 | nodejs
Full support
10.0.0
|
Unicode property escapes (\p{...}) | Chrome Full support 64 | Edge Full support 79 | Firefox No support No | IE No support No | Opera Full support 51 | Safari Full support 11.1 | WebView Android Full support 64 | Chrome Android Full support 64 | Firefox Android No support No | Opera Android Full support 47 | Safari iOS Full support 11.3 | Samsung Internet Android Full support 9.0 | nodejs
Full support
10.0.0
|
RegExp.rightContext ($') | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 8 | Safari Full support 3 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
source | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
sticky | Chrome Full support 49 | Edge Full support 13 | Firefox Full support 3 | IE No support No | Opera Full support 36 | Safari Full support 10 | WebView Android Full support 49 | Chrome Android Full support 49 | Firefox Android Full support 4 | Opera Android Full support 36 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support Yes |
test | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
toSource | Chrome No support No | Edge No support No | Firefox
No support
1 — 74
| IE No support No | Opera No support No | Safari No support No | WebView Android No support No | Chrome Android No support No | Firefox Android Full support 4 | Opera Android No support No | Safari iOS No support No | Samsung Internet Android No support No | nodejs No support No |
toString | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
unicode | Chrome Full support 50 | Edge
Full support
12
| Firefox Full support 46 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 46 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support Yes |
@@match | Chrome Full support 50 | Edge Full support 13 | Firefox Full support 49 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 49 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
@@matchAll | Chrome Full support 73 | Edge Full support 79 | Firefox Full support 67 | IE No support No | Opera Full support 60 | Safari No support No | WebView Android Full support 73 | Chrome Android Full support 73 | Firefox Android Full support 67 | Opera Android Full support 52 | Safari iOS No support No | Samsung Internet Android Full support 5.0 | nodejs Full support 12.0.0 |
@@replace | Chrome Full support 50 | Edge Full support 79 | Firefox Full support 49 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 49 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
@@search | Chrome Full support 50 | Edge Full support 13 | Firefox Full support 49 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 49 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
@@species | Chrome Full support 50 | Edge Full support 13 | Firefox Full support 49 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 49 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs
Full support
6.5.0
|
@@split | Chrome Full support 50 | Edge Full support 79 | Firefox Full support 49 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 49 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
Legend
- Full support
- Full support
- No support
- No support
- 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.