簡體   English   中英

使用正則表達式替換 email 字符串中倒數第二個字符(點)

[英]Replace second last occurrence of a char(dot) in an email string using regex

請我想替換 a 中倒數第二個出現的字符,字符串的長度可能會有所不同,但分隔符始終相同我將在下面給出一些示例以及我嘗試過的輸入 1:james.sam.uri.stackoverflow .com

Output 1:james.sam.uri@stackoverflow.com

輸入 2:noman.stackoverflow.com

Output 2:noman@stackoverflow.com

輸入 3:queen.elizabeth.empire.co.uk

Output 3:queen.elizabeth@empire.co.uk

我的解決方案

//This works but I don't want this as its not a regex solution
const e = "noman.stackoverflow.com"
var index = e.lastIndexOf(".", email.lastIndexOf(".")-1)
return ${e.substring(0,index)}@${e.substring(index+1)}

Regex
e.replace(/\.(\.*)/, @$1)
//this works for Input 2 not Input 1, i need regex that would work for both, it only matches the first dot

倒數第二個點的示例數據中的問題是最后一個示例以.co.uk結尾

這些特定示例的一個選項可能是使用模式來排除該特定部分。

(\S+)\.(?!co\.uk$)(\S*?\.[^\s.]+)$
  • (\S+)捕獲組 1 ,匹配 1+ 非空白字符
  • \.(?.co\.uk$)匹配一個. 后跟一個直接向右的否定前瞻斷言不是co.uk
  • (捕獲組 2
    • \S*?\. 匹配 0+ 次非 whitspace char 非貪婪,然后是.
    • [^\s.]+匹配 1+ 次非空白字符,除了.
  • )關閉第 2 組
  • $字符串結尾

查看正則表達式演示

 [ "james.sam.uri.stackoverflow.com", "noman.stackoverflow.com", "queen.elizabeth.empire.co.uk" ].forEach(s => console.log(s.replace(/(\S+)\.(?.co\?uk$)(\S*.\.[^\s,]+)$/; "$1@$2")) );

這是另一種方法:

(\S+)\.(\S+\.\S{3,}?)$
       (            )$  At the end of the string, capture by
             \S{3,}?    lazily matching 3+ non-whitespace characters
        \S+\.           and any non-whitespace characters with period in front.
(\S+)\.                 Also capture anything before the separating period.

值得注意的是,對於像test.stackoverflow.co.net這樣的 email 來說,它會失敗。 如果該格式是必需的,我會推薦一種不同的方法。

 [ "james.sam.uri.stackoverflow.com", "noman.stackoverflow.com", "queen.elizabeth.empire.co.uk", "test.stackoverflow.co.net" ].forEach(s => console.log(s.replace(/(\S+)\.(\S+\.\S{3,}?)$/, "$1@$2")) );

暫無
暫無

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

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