簡體   English   中英

如何替換字符串中第一次出現的模式

[英]How to replace all BUT the first occurrence of a pattern in string

快速問題:我的模式是一個 svg 字符串,它看起來像l 5 0 l 0 10 l -5 0 l 0 -10要與參考進行一些單元測試比較,我需要放棄所有,但我知道我可以放棄第一個l all 並在前面放一個“l”,或者我可以使用子字符串。 但我想知道是否有一個 javascript regexp 成語?

您可以嘗試否定前瞻,避免字符串的開頭:

/(?!^)l/g

在線查看: 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"

為每個匹配執行函數 ( fn_replaceBy )。 在第一次匹配時,該函數立即返回匹配的字符串(什么也沒發生),並設置一個標志。
每隔一個匹配項將根據函數中描述的邏輯進行替換:通常,您使用$0 $1 $2等來引用組。 fn_replaceBy ,函數參數等於這些:第一個參數 = $0 ,第二個參數 = $1 ,等等。

匹配的子字符串將被函數fn_replaceBy的返回值fn_replaceBy 使用函數作為replace的第二個參數允許非常強大的應用程序,例如智能 HTML 解析器

另請參閱: MDN:String.replace > 將函數指定為參數

這不是最漂亮的解決方案,但您可以用任意的東西(如占位符)和鏈替換來替換第一次出現,以完成其余的邏輯:

'-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

產生:

-983247924234.01

對於任何尋找不能依賴於第一個匹配/出現是字符串中的第一個字符的示例的人來說,這只是擴展了公認的答案。

 "l 5 0 l 0 10 l -5 0 l 0 -10".replace(/^\s+/, '').replace(/\s+l/g, '')

確保第一個'l'前面沒有空格,並刪除后跟'l'任何空格。

標記的分析服務程序實質上是錯誤的,第一次出現並不意味着字符串以該模式開頭。

我在https://www.regextester.com/99881 上找到了這個解決方案,使用了后視模式:

/(?<=(.*l.*))l/g

或更一般地

/(?<=(.*MYSTRING.*))MYSTRING/g

其中MYSTRING是您要刪除的內容。

(順便說一下,這也可能是一個有用的字符串,用於刪除電子郵件主題字符串中除第一次出現的“Re:”之外的所有內容。)

像這樣的東西?

"l 5 0 l 0 10 l -5 0 l 0 -10".replace(/[^^]l/g, '')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM