모든 선행 탭 문자를 하나의 공백으로 바꾸는 정규식 [중복]

Nov 24 2020

모든 선행 탭 문자를 단일 공백으로 바꾸는 정규식을 찾고 있습니다 (각 선행 탭 문자에 대해 하나의 공백.

// input text with two leading tab characters and two tab characters elsewhere in the text
var input="     Some text       containing tabs";

// A:
console.log(input.replace(/\t/g, "LEADING_TAB_"));  
// prints: "LEADING_TAB_LEADING_TAB_Some textLEADING_TAB_LEADING_TAB_containing tabs"

// B:
console.log(input.replace(/\t/, "LEADING_TAB_"));  
// prints: "LEADING_TAB_   Some text       containing tabs"

// C:
console.log(input.replace(/^(\t)*/, "LEADING_TAB_"));  
// prints: "LEADING_TAB_Some text      containing tabs"

// D:
console.log(input.replace(/\t/gy, "LEADING_TAB_"));  
// prints: "LEADING_TAB_LEADING_TAB_Some text      containing tabs"

// E:
console.log(input.replace(/\t/y, "LEADING_TAB_"));  
// prints: "LEADING_TAB_   Some text       containing tabs"

js 바이올린에서 이것을 참조하십시오. https://jsfiddle.net/onebcvu4/2/

대답 D는 나를 위해 일합니다.

input.replace(/\t/gy, " ")

그러나 나는 그 이유를 정말로 이해하지 못한다. 특히 MDN 문서 에 따르면 스티키 플래그와 함께 사용할 때는 전역 (G) 플래그를 무시해야하기 때문입니다.

고정 및 전역으로 정의 된 정규식은 전역 플래그를 무시합니다.

누구든지 명확하게 표현하거나 작동하는 다른 솔루션을 제공 할 수 있습니까?

답변

2 T.J.Crowder Nov 24 2020 at 14:46

귀하의 응답 D 작동 (그리고 아주 똑똑) 때문에 gy 없는 독점하지만, 그들이 될 것이라고 생각하는 것이 합리적이다. 자세한 내용은 here 및 here 사양 에 있지만 기본적 으로 일치 g하는 한 replace반복되며 yA) 표현식이 lastIndex(기본값은 0) 에서만 일치 하고 B) lastIndex는 업데이트되지 않음을 의미합니다. 반복적으로 일치 그래서 \t에서 lastIndex그것을 대체 당신은 밖으로 실행할 때까지 \t에서 lastIndex. 매우 영리한.

그것을 사용하고 싶지 않다면, 교대하고 긍정적 인 모습으로 할 수도 있습니다.

const result = input.replace(/(?:^\t|(?<=^\t*)\t)/g, " ");

라이브 예 :

const input = "\t\tSome text\t\tcontaining tabs";
const result = input.replace(/(?:^\t|(?<=^\t*)\t)/g, " ");

console.log(JSON.stringify(result));

또는 콜백을 replace에 전달해도 괜찮다면 더 간단하고 lookbehind가 필요하지 않습니다 (비교적 새로운 ES2018) : 모든 선행 \t문자를 일치 시키고 동일한 길이의 공백 문자열로 바꿉니다 .

const result = input.replace(/^(\t+)/, match => " ".repeat(match.length));

라이브 예 :

const input = "\t\tSome text\t\tcontaining tabs";
const result = input.replace(/^(\t+)/, match => " ".repeat(match.length));
console.log(JSON.stringify(result));