我有一些我之前写过的php函数。然而,现在,我正在将一些解析/匹配移动到客户端。
function artist_name_to_regex($art_name){
$regex_part = preg_quote($art_name);
$regex_part = preg_replace('('|\')', '.+', $regex_part);
$regex_part = preg_replace('/ /i', '\s?', $regex_part);
$regex_part = preg_replace('/(and|&|&|\+)/i', '(and|&|&|\+)', $regex_part);
return $regex_part;
}
我想从js中这样称呼它:
var regex = artist_name_to_regex('David & the Smokey Sea Horses!');
if(some_str.match(/regex/ig)){
alert('match found!');
}
我需要修改top函数,以便:
a)是用javascript编写的
b)返回一个可以使用javascipt
的正则表达式答案 0 :(得分:1)
为什么需要构造这样的正则表达式?看起来好像你需要知道一个字符串是否出现在另一个字符串中......
这样可以更容易地进行测试:
if (some_str.indexOf('David & the Smokey Sea Horses!') !== -1) {
alert('match found!');
}
否则,从字符串创建正则表达式相当容易:
function createRegex(pattern) {
pattern = pattern.replace(/'/g, '.+');
pattern = pattern.replace(/ /g, '\\s?');
pattern = pattern.replace(/(and|&|&|\+)/ig, '(and|&|&|\\+)');
return new RegExp(pattern, 'gi');
}
var customRegex = createRegex('David & the Smokey Sea Horses!');
if (some_str.match(customRegex)) {
alert('match found!');
}