dr *_*rry 19 javascript regex regex-negation
快速问题:我的模式是一个svg字符串,它看起来像l 5 0 l 0 10 l -5 0 l 0 -10做一个单位测试比较我需要抛弃所有,但第一个l我知道我可以抛弃所有并提前'l',或者我可以使用子串.但我想知道这有一个javascript正则表达式成语吗?
Mar*_*ers 30
您可以尝试使用负向前瞻,避免字符串的开头:
/(?!^)l/g
Run Code Online (Sandbox Code Playgroud)
看看是否在线:jsfiddle
没有JS RegExp来替换所有东西 - 但是第一个模式匹配.但是,您可以通过将函数作为第二个参数传递给replace方法来实现此行为.
var regexp = /(foo bar )(red)/g; //Example
var string = "somethingfoo bar red foo bar red red pink foo bar red red";
var first = true;
//The arguments of the function are similar to $0 $1 $2 $3 etc
var fn_replaceBy = function(match, group1, group2){ //group in accordance with RE
if (first) {
first = false;
return match;
}
// Else, deal with RegExp, for example:
return group1 + group2.toUpperCase();
}
string = string.replace(regexp, fn_replaceBy);
//equals string = "something foo bar red foo bar RED red pink foo bar RED red"
Run Code Online (Sandbox Code Playgroud)
fn_replaceBy每个匹配都执行function().在第一次匹配时,函数立即返回匹配的字符串(没有任何反应),并设置一个标志.
每个其他匹配将根据函数中描述的逻辑进行替换:通常,您使用$0 $1 $2等等来引用组.在fn_replaceBy,函数参数等于:First argument = $0,second argument = $1,et cetera.
匹配的子字符串将被函数的返回值替换fn_replaceBy.使用函数作为第二个参数可以replace实现非常强大的应用程序,例如智能HTML解析器.
另请参见:MDN:String.replace>将函数指定为参数