<aside> <img src="/icons/search_gray.svg" alt="/icons/search_gray.svg" width="40px" /> 영어에서 Contraction(축약/단축형)과 Abbreviation(약어/축약어)는 다른 개념이다.
I will → I’ll, do not → don'tUnited States → U.S., Doctor → Dr.
</aside>// 단어 문자가 아닌 문자열과 일치
const NonWordCharPattern = /(\\W)/g;
const sentence = "I'll make coffee and I've done my homework."
// 단어 문자가 아닌 문자열 양쪽에 공백 추가 e.g. '.' → ' . '
const replaced = sentence.replace(NonWordCharPattern, " $1 ");
// "I ' ll make coffee and I ' ve done my homework . "
replaced.split(/\\s+/);
// ['I', "'", 'll', 'make', 'coffee', 'and', 'I', "'", 've', 'done', 'my', 'homework', '.', '']
\\W 메타문자는 공백을 포함한 단어문자(0-9a-zA-Z_)가 아닌 것을 가리킨다$1은 첫번째 캡처 그룹(소괄호)을 가리킴. 위 예시에선 쉼표 ,와 공백 `` 을 한 번씩 참조'Hello, World'.replace(/(\\W)/g, ' $1 ') → 'Hello , World’
$1 참조값 : , → ,$1 참조값 : (length 1) → (length 3)// 단어 문자나 아포스트로피(')가 아닌 모든 문자와 일치
const NonWordCharPattern = /([^\\w'])/g;
// 단어 문자나 아포스트로피가 아닌 문자열 양쪽에 공백 추가 e.g. ' ' → ' '
const replaced = "I'll make coffee and I've done my homework.".replace(NonWordCharPattern, " $1 ");
// "I'll make coffee and I've done my homework . "
replaced.split(/\\s+/);
// ["I'll", 'make', 'coffee', 'and', "I've", 'done', 'my', 'homework', '.', '']
/([^\\w'])/g : 단어 문자나 아포스트로피(')가 아닌 모든 문자와 일치 (공백, 쉼표 등)
[] : 문자 그룹. 대괄호에 있는 문자열 중 하나라도 일치하면 매칭[^] : 부정 문자 그룹. 대괄호의 시작이 캐럿(^) 일 땐 대괄호에 해당하지 않는 문자열만 매칭split(/\\s+/) : 하나 이상의 연속된 공백을 기준으로 분리
\\s : 공백 문자+ : 1번 이상 일치'Hello , World'.split(/\\s+/) → ['Hello', ',', 'World']
['Hello', ', World']`` 두번째 공백으로 분리 후 `['Hello', ',' ,'World']`
const ContractionPattern = /\\b\\w+'\\w*\\b/;
const findContrIndexes = (arr: string[]) => {
return arr.reduce((acc: number[], cur, i) => {
return ContractionPattern.test(cur) ? acc.concat(i) : acc;
}, []);
};
findContrIndexes(["I'll", 'make', 'coffee', 'and', "I've", 'done', 'my', 'homework', '.'])
// 반환값 [0, 4]
I've can't 등 다양한 축약 케이스를 식별하기 위해 /\\b\\w+'\\w*\\b/ 정규식 사용. \\w+' 는 아포스트로피(') 기준 앞에 있는 부분이고, \\w* 는 뒤에 있는 부분.
\\b : 단어 경계(앞 혹은 뒤에 다른 단어 문자가 등장하지 않는 위치)\\w+' : 1개 이상의 연속된 단어 문자 뒤에 아포스트로피가 있는 문자와 일치\\w* : 0개 이상의 연속된 단어 문자