반응형
Javascript 정규식에 사용하기위한 이스케이프 문자열
가능한 중복 :
Javascript에 RegExp.escape 함수가 있습니까?
사용자 입력을 기반으로 자바 스크립트 정규식을 작성하려고합니다.
FindString (입력) 기능 { var reg = new RegExp ( ''+ 입력 + ''); // [snip] 검색 수행 }
그러나 사용자 입력에 ?
또는 *
정규 표현식 스페셜로 해석되기 때문에 정규 표현식이 올바르게 작동하지 않습니다 . 실제로 사용자가 불균형 (
또는 [
문자열을 넣으면 정규 표현식도 유효하지 않습니다.
정규식에 사용하기 위해 모든 특수 문자를 올바르게 이스케이프하는 Javascript 함수는 무엇입니까?
짧고 달콤한
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
예
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
설치
npm에서 escape-string-regexp 로 사용 가능
npm install --save escape-string-regexp
노트
MDN : Javascript 안내서 : 정규식을 참조하십시오 .
다른 기호 (~`! @ # ...)는 결과없이 이스케이프 될 수 있지만 반드시 그럴 필요는 없습니다.
.
.
.
.
테스트 사례 : 일반적인 URL
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
긴 대답
위의 함수를 사용하려는 경우 코드 문서 에서이 스택 오버플로 게시물에 링크하여 테스트하기 어려운 부두교처럼 보이지 않도록하십시오.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());
참고 URL : https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
반응형
'Programming' 카테고리의 다른 글
왜 수업보다 구조를 선택해야합니까? (0) | 2020.02.15 |
---|---|
Java의 다른 클래스에서 개인 필드의 값을 읽는 방법은 무엇입니까? (0) | 2020.02.15 |
Windows 명령 줄 환경을 사용하여 파일에서 텍스트를 찾고 바꾸는 방법은 무엇입니까? (0) | 2020.02.15 |
현재 실행중인 파일의 경로와 이름은 어떻게 얻습니까? (0) | 2020.02.15 |
Windows의 명령 줄에서 빈 파일을 만드는 방법은 무엇입니까? (0) | 2020.02.15 |