[2023-09-21] TIL - 정규표현식
정규표현식
정규표현식의 목적
- 패턴을 이용하여 문자를 검색, 대체, 추출 한다.
- 성능은 느리지만 편함
정규표현식 사이트
Rubular
Ruby-based regular expression editor/tester
rubular.com
정규표현식 표현
정규표현식연습 사이트
RegexOne - Learn Regular Expressions - Lesson 1: An Introduction, and the ABCs
Regular expressions are extremely useful in extracting information from text such as code, log files, spreadsheets, or even documents. And while there is a lot of theory behind formal languages, the following lessons and examples will explore the more prac
regexone.com
http://alf.nu/RegexGolf?world=regex&level=r00
Regex Golf
alf.nu
자바스크립트에서 사용하는 방법
const re = new RegExp("ab+c");
const re = /ab+c/;
1. test
const str = 'table football';
const regex = new RegExp('foo*');
const globalRegex = new RegExp('foo*', 'g');
console.log(regex.test(str));
// Expected output: true
- 정규표현식에 해당하는 패턴이 있다면 true를 반환하고 없다면 false
2. exec
- 입력받은 문자열에 찾는 패턴이 있는지 찾은 후 일치한 패턴 정보를 반환하고 없으면 null을 반환한다.
- 문자 추출에 해당한다.
const regex1 = RegExp('foo*', 'g');
const str1 = 'table football, foosball';
let array1;
while ((array1 = regex1.exec(str1)) !== null) {
console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
// Expected output: "Found foo. Next starts at 9."
// Expected output: "Found foo. Next starts at 19."
}
3. match
- exec와 동일하다.
const re = /[abc]/y;
for (let i = 0; i < 5; i++) {
console.log("abc".match(re), re.lastIndex);
}
// [ 'a' ] 1
// [ 'b' ] 2
// [ 'c' ] 3
// null 0
// [ 'a' ] 1
4. matchAll
- 매칭된 모든 케이스를 반환한다.
const regexp = /[a-c]/g;
regexp.lastIndex = 1;
const str = "abc";
Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
// [ "1 b", "1 c" ]
5. replace
- 일치한 패턴 정보를 원하는 문자열로 바꿀 수 있다.
- 모두 변경하고 싶다면 플래그에 g를 입력하면 된다.
const re = /a/y;
for (let i = 0; i < 5; i++) {
console.log("aaa".replace(re, "b"), re.lastIndex);
}
// baa 1
// aba 2
// aab 3
// aaa 0
// baa 1
6. search
- 일치한 패턴 정보의 위치를 반환한다.
- 무조건 처음 발견한 정보만을 반환한다.
const re = /[abc]/g;
re.lastIndex = 2;
console.log("abc".search(re)); // 0
const re2 = /[bc]/y;
re2.lastIndex = 1;
console.log("abc".search(re2)); // -1
console.log("abc".match(re2)); // [ 'b' ]
7. capture
- 캡처가 적용된 정규표현식을 이용하면 match 반환값의 1번 인덱스부터 순차적으로 캡처 결과가 들어간다.
'javascript'.replace(/(java)(script)/, `$2-$1`) // script-java
Run-length-encoding
- 매우 간단한 비손실 압축 방법
- "AAAAAABBBDFFFFFFFKK" 문자열을 어떻게 압축할 것인가
-> "6A3B1D7F2K" 로 압축해야한다.
const raw = "AAAAAABBBDFFFFFFFKK"
const regExp = /(.)\1*/G;
const result = raw.match(regExp).reduce((a,b)=> a+ `${b.length}${b.slice(0, 1)}`,"");
console.log(result) //"6A3B1D7F2K"