[英]How to check if the input string is a valid Regular expression?
在 JavaScript 中,您如何檢查字符串是否是可以編譯的正確正則表達式?
例如,當您執行以下 javascript 時,它會產生錯誤。
var regex = new RegExp('abc ([a-z]+) ([a-z]+))');
// produces:
// Uncaught SyntaxError: Invalid regular expression: /abc ([a-z]+) ([a-z]+))/: Unmatched ')'
如何確定一個字符串是否是有效的正則表達式?
您可以使用try/catch
和RegExp
構造函數:
var isValid = true;
try {
new RegExp("the_regex_to_test_goes_here");
} catch(e) {
isValid = false;
}
if(!isValid) alert("Invalid regular expression");
這是一個小函數,用於檢查兩種類型的正則表達式、字符串或模式的有效性:
function validateRegex(pattern) {
var parts = pattern.split('/'),
regex = pattern,
options = "";
if (parts.length > 1) {
regex = parts[1];
options = parts[2];
}
try {
new RegExp(regex, options);
return true;
}
catch(e) {
return false;
}
}
例如,用戶將能夠測試test
和/test/g
。 這是一個工作小提琴。
此函數可以將 '/' 字符作為正則表達式中的普通字符處理,並且還可以考慮轉義 when 是常見字符串。 它將始終返回一個正則表達式,如果不是一個好的正則表達式字符串,則為 null。
function getRegex(regex) { try { regex = regex.trim(); let parts = regex.split('/'); if(regex[0] !== '/' || parts.length< 3){ regex = regex.replace(/[.*+\\-?^${}()|[\\]\\\\]/g, '\\\\$&'); //escap common string return new RegExp(regex); } const option =parts[parts.length - 1]; const lastIndex = regex.lastIndexOf('/'); regex = regex.substring(1, lastIndex); return new RegExp(regex, option); } catch (e) { return null } } console.log(getRegex('ab/c')) let htmlStartTag = getRegex('/<(?!/)(?!br)(.+?)(?<!/)>/mgs'); console.log(htmlStartTag) let result = `</button><input id="warehouse-search-field-tablet" class="form-control search-field" title="Warehouse Search Field" name="location" type="search" value="">content`.matchAll(htmlStartTag); console.log([...result])
問題解決了,但是如果有人需要定義字符串是有效的RegExp還是根本不是RegExp 。
如前所述,您可以使用new Function()
並在函數體內使用try ... catch
和new RegExp()
模板化。
有一段解釋:
const isRegExp = (string) => { try { return new Function(` "use strict"; try { new RegExp(${string}); return true; } catch (e) { return false; } `)(); } catch(e) { return false; } }; // Here the argument 'simplyString' shall be undefined inside of the function // Function(...) catches the error and returns false console.log('Is RegExp valid:', isRegExp('simplyString')); // Here the argument shall cause a syntax error // isRegExp function catches the error and returns false console.log('Is RegExp valid:', isRegExp('string which is not a valid regexp')); // Here the argument is not a valid RegExp, new RegExp(...) throws an error // Function(...) catches the error and returns false console.log('Is RegExp valid:', isRegExp('abc ([az]+) ([az]+))')); // Valid RegExp, passed as a string console.log('Is RegExp valid:', isRegExp('/^[^<>()[\\]\\\\.,;:\\s@\\"]$/')); // Valid RegExp, passed as a RegExp object console.log('Is RegExp valid:', isRegExp(/^[^<>()[\\]\\\\.,;:\\s@\\"]$/)); // Howewer, the code injection is possible here console.log('Is RegExp valid:', isRegExp(');console.log("This is running inside of the Function(...) as well"'));
這里的答案都不能滿足我檢查字符串是否是其他語言(主要是 php)的有效正則表達式的需要,因為它們要么忽略標志、分隔符或轉義特殊字符,所以我制作了自己的函數
function isValidRegex(s) { try { const m = s.match(/^([/~@;%#'])(.*?)\\1([gimsuy]*)$/); return m ? !!new RegExp(m[2],m[3]) : false; } catch (e) { return false } } console.log(isValidRegex('abc')) //False console.log(isValidRegex('/abc/')) //True console.log(isValidRegex('/ab#\\/[c]/ig')) //True console.log(isValidRegex('@ab#\\/[c]@ig')) //Special delimiters: True console.log(isValidRegex('/ab\\/[c/ig')) //False console.log(isValidRegex('/abc/gig')) //False
你也可以派生出這個函數來將一個字符串轉換成一個 RegExp 對象
function stringToRegex(s) { const m = s.match(/^([/~@;%#'])(.*?)\\1([gimsuy]*)$/); return m ? new RegExp(m[2], m[3]) : new RegExp(s); } console.log(stringToRegex('abc')) console.log(stringToRegex('/abc/')) console.log(stringToRegex('/ab#\\/[c]/ig')) console.log(stringToRegex('@ab#\\/[c]@ig')) try { console.log(stringToRegex('/ab#\\/[c/ig')) } catch (e) { console.log('Not a valid regex') }
function isRegExp(regExp){
try {
new RegExp(regExp);
} catch(e) {
return false
}
return true
}
ex:
isRegExp(/@(\w+)/g) = true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.