javascript 如何替换所有但字符串中第一次出现的模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7959975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace all BUT the first occurrence of a pattern in string
提问by dr jerry
quick question: my pattern is an svg string and it looks like l 5 0 l 0 10 l -5 0 l 0 -10
To do some unittest comparison against a reference I need to ditch all but the first l
I know i can ditch them all and put an 'l' upfront, or I can use substrings. But I'm wondering is there a javascript regexp idiom for this?
快速问题:我的模式是一个 svg 字符串,它看起来像l 5 0 l 0 10 l -5 0 l 0 -10
要对参考进行一些单元测试比较,我需要l
放弃所有,但首先我知道我可以放弃它们并在前面放置一个 'l',或者我可以使用子字符串。但我想知道是否有一个 javascript regexp 成语?
回答by Mark Byers
回答by Rob W
There's no JS RegExp to replace everything-but-the-first-pattern-match. You can, however, implement this behaviour by passing a function as a second argument to the replace
method.
没有 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 "l 5 0 l 0 10 l -5 0 l 0 -10".replace(/^\s+/, '').replace(/\s+l/g, '')
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"
The function (fn_replaceBy
) is executed for each match. At the first match, the function immediately returns with the matched string (nothing happens), and a flag is set.
Every other match will be replaced according to the logic as described in the function: Normally, you use $0 $1 $2
, et cetera, to refer back to groups. In fn_replaceBy
, the function arguments equal these: First argument = $0
, second argument = $1
, et cetera.
fn_replaceBy
为每个匹配执行函数 ( )。在第一次匹配时,该函数立即返回匹配的字符串(什么也没发生),并设置一个标志。
将根据函数中描述的逻辑替换所有其他匹配项:通常,您使用$0 $1 $2
等来引用组。在 中fn_replaceBy
,函数参数等于这些:第一个参数 = $0
,第二个参数 =$1
等等。
The matched substring will be replaced by the return value of function fn_replaceBy
. Using a function as a second parameter for replace
allows very powerful applcations, such as an intelligent HTML parser.
匹配的子字符串将被 function 的返回值替换fn_replaceBy
。使用函数作为第二个参数replace
允许非常强大的应用程序,例如智能 HTML 解析器。
See also: MDN: String.replace > Specifying a function as a parameter
回答by Mike Samuel
'-98324792u4234jkdfhk.sj.dh-f01' // construct valid float
.replace(/[^\d\.-]/g, '') // first, remove all characters that aren't common
.replace(/(?!^)-/g, '') // replace negative characters that aren't in beginning
.replace('.', '%FD%') // replace first occurrence of decimal point (placeholder)
.replace(/\./g, '') // now replace all but first occurrence (refer to above)
.replace(/%FD%(0+)?$/, '') // remove placeholder if not necessary at end of string
.replace('%FD%', '.') // otherwise, replace placeholder with period
makes sure the first 'l'
is not preceded by space and removes any space followed by an 'l'
.
确保第一个'l'
前面没有空格,并删除后面跟有'l'
.
回答by Erutan409
It's not the prettiest solution, but you could replace the first occurrence with something arbitrary (like a placeholder) and chain replacements to fulfill the rest of the logic:
这不是最漂亮的解决方案,但您可以用任意的东西(如占位符)和链替换来替换第一次出现,以实现其余的逻辑:
##代码##Produces:
产生:
-983247924234.01
-983247924234.01
This merely expands on the accepted answer for anyone looking for an example that can't depend on the first match/occurrence being the first character in the string.
对于任何寻找不能依赖于第一个匹配/出现是字符串中的第一个字符的示例的人来说,这只是扩展了公认的答案。
回答by Supernormal
I found this solution at https://www.regextester.com/99881, using a lookbehind pattern:
我在https://www.regextester.com/99881 上找到了这个解决方案,使用了后视模式:
/(?<=(.*l.*))l/g
/(?<=(.*l.*))l/g
Or more generally
或更一般地
/(?<=(.*MYSTRING.*))MYSTRING/g
/(?<=(.*MYSTRING.*))MYSTRING/g
where MYSTRING
is something that you want to remove.
MYSTRING
您要删除的内容在哪里。
(This may also be a useful string for removing all but the first occurrence of "Re:" in an email subject string, by the way.)
(顺便说一下,这也可能是一个有用的字符串,用于删除电子邮件主题字符串中除第一次出现的“Re:”之外的所有内容。)
回答by Mic
Something like this?
像这样的东西?
"l 5 0 l 0 10 l -5 0 l 0 -10".replace(/[^^]l/g, '')
"l 5 0 l 0 10 l -5 0 l 0 -10".replace(/[^^]l/g, '')