정규표현식(Regular Expression) 활용
이전 포스트에서 정규표현식의 기본적인 개념과 자바스크립트에서 정규표현식을 사용하는 법을 알아보았다. 이번에는 정규표현식 사용을 위한 자바스크립트 메소드와 정규표현식을 유용하게 사용하는 방법을 알아보자.
정규표현식을 사용하는 메소드
RegExp.prototype.exec()
대응되는 문자열을 찾아서 배열로 반환하는 RegExp 메소드. 대응되는 문자열이 없다면 null을 반환.
const myRegex = /.+(Seoul|Incheon)/;
const result = myRegex.exec("I live in Seoul");
console.log(result);
[
'I live in Seoul',
'Seoul',
index: 0,
input: 'I live in Seoul',
groups: undefined
]
RegExp.prototype.test()
대응되는 문자열이 있는지 확인하는 RegExp 메소드. 대응되는 문자열의 존재유무에 따라서 true, false 반환.
const myRegex = /(Seoul|Incheon)/;
const result = myRegex.test("I live in Seoul");
console.log(result);
true
String.prototype.match()
대응되는 문자열을 찾아주는 String 메소드. 정규식에 g 플래그가 없다면 RegExp의 exec()메소드와 같은 결과를 반환한다.
const myRegex = /(Seoul|Incheon)/;
console.log(myRegex.exec("I live in Seoul, I love Incheon"));
console.log("I live in Seoul, I love Incheon".match(myRegex));
[
'Seoul',
'Seoul',
index: 10,
input: 'I live in Seoul, I love Incheon',
groups: undefined
]
[
'Seoul',
'Seoul',
index: 10,
input: 'I live in Seoul, I love Incheon',
groups: undefined
]
정규식에 g 플래그가 포함되어있다면 대응되는 문자열을 담고있는 배열을 반환하는데 이 배열은 exec()의 반환값처럼 다른 부가적인 정보를 가지고 있지 않다.
const myRegex = /(Seoul|Incheon)/g;
console.log(myRegex.exec("I live in Seoul, I love Incheon"));
console.log("I live in Seoul, I love Incheon".match(myRegex));
[
'Seoul',
'Seoul',
index: 10,
input: 'I live in Seoul, I love Incheon',
groups: undefined
]
[ 'Seoul', 'Incheon' ]
String.prototype.search()
처음으로 대응되는 문자열의 첫 번째 인덱스를 반환하는 String 메소드. 대응되는 문자열이 없다면 -1을 반환.
const myRegex = /(Seoul|Incheon)/;
const result = "I live in Seoul".search(myRegex);
console.log(result);
10
String.prototype.replace()
대응되는 일부 문자열 또는 모든 문자열이 교체된 새로운 문자열을 반환한다.
const myRegex = /(Seoul|Incheon)/;
const result = "I live in Seoul, I love Incheon".replace(myRegex, "Busan");
console.log(result);
const myRegex2 = /(Seoul|Incheon)/g;
const result2 = "I live in Seoul, I love Incheon".replace(myRegex2, "Busan");
console.log(result2);
I live in Busan, I love Incheon
I live in Busan, I love Busan
References
https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/%EC%A0%95%EA%B7%9C%EC%8B%9D