簡體   English   中英

替換之前的任何字符<usernameredacted@example.com>有一個空字符串</usernameredacted@example.com>

[英]Replace any character before <usernameredacted@example.com> with an empty string

我有這個字符串

     AnyText: "jonathon" <usernameredacted@example.com>

使用正則表達式所需的 Output

     AnyText: <usernameredacted@example.com>

省略中間的任何內容!

我仍然是正則表達式的新手。 有人可以幫我解決上述場景的匹配和替換表達式嗎?

嘗試這個:

string input = "jonathon <usernameredacted@example.com>";
string output = Regex.Match(input, @"<[^>]+>").Groups[0].Value;
Console.WriteLine(output); //<usernameredacted@example.com>

您可以使用以下正則表達式來匹配要替換為空字符串的所有字符:

^[^<]*

第一個^是字符串開頭的錨點。 字符 class 中的^表示字符 class 是否定的。 IE。 任何不是<的字符都將匹配。 *是一個貪婪的量詞。 所以總而言之,這個正則表達式將吞噬從字符串開頭到第一個<的所有字符。

這是 VBA 風格的方法:將“^[^”“]*”替換為“”。

  • ^ 標記句子的開始。
  • [^""]* 標記除引號之外的任何內容。

更新:由於在您的附加評論中您提到您想要獲取“發件人:”和 email 地址,但在兩者之間或之后沒有任何垃圾,我認為不是替換,而是提取會更好。 這是為 Excel 編寫的 VBA function ,它將返回所有子組匹配項(括號中的所有內容),僅此而已。

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String) As String

Application.ScreenUpdating = False
Dim i As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.Pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.Item(0).submatches.count - 1
    result = result & allMatches.Item(0).submatches.Item(i)
Next

RegexExtract = result
Application.ScreenUpdating = True

End Function

使用此代碼,您的正則表達式調用將是: "^(.+: ).+(<.+>).*"

  • ^ 表示句首
  • (.+: ) 表示第一個匹配組。 .+ 是一個或多個字符,后跟:和一個空格
  • .+ 表示一個或多個字符
  • (<.+>) 表示第二個匹配組。 < 是 <,然后 .+ 表示一個或多個字符,然后是最后一個 >
  • .* 表示零個或多個

    人物。

所以在 excel 中你會使用(假設單元格是 A1):

=RegexExtract(A1, "^(.+: ).+(<.+>).*")

暫無
暫無

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

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