javascript - 추출 - 정규표현식 특수문자
자바 스크립트 정규 표현식에서 사용하기위한 이스케이프 문자열 (1)
짧고 달콤한
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 Guide : Regular Expressions를 참조하십시오 .
다른 기호 (~`! @ # ...)는 결과없이 이스케이프 될 수 있지만 반드시 필요하지는 않습니다.
.
.
.
.
테스트 케이스 : 일반적인 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 "[email protected]#$%^&*(){}[]`/=?+\|-_;:'\",<.>".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")
}());
가능한 중복 :
Javascript에 RegExp.escape 함수가 있습니까?
사용자 입력을 기반으로 자바 스크립트 정규식을 작성하려고합니다.
function FindString(input) { var reg = new RegExp('' + input + ''); // [snip] perform search }
하지만 사용자 입력에 ?
가 포함되어 있으면 정규식이 제대로 작동하지 않습니다 ?
또는 *
정규식 스페셜로 해석되기 때문입니다. 사실, 사용자가 불균형을 넣으면 (
또는 [
문자열에 정규식이 유효하지 않습니다.
regex에서 사용하기 위해 모든 특수 문자를 올바르게 이스케이프 처리하는 javascript 함수는 무엇입니까?