簡體   English   中英

從C#中的字符串中提取最后一個匹配項

[英]extract last match from string in c#

我有[abc].[some other string].[can.also.contain.periods].[our match]形式的字符串[abc].[some other string].[can.also.contain.periods].[our match]

我現在想匹配字符串“我們的匹配”(即不帶括號),所以我玩了環視和其他功能。 我現在得到了正確的比賽,但是我認為這不是一個干凈的解決方案。

(?<=\.?\[)     starts with '[' or '.['
([^\[]*)      our match, i couldn't find a way to not use a negated character group
              `.*?` non-greedy did not work as expected with lookarounds,
              it would still match from the first match
              (matches might contain escaped brackets)
(?=\]$)       string ends with an ]

語言是.net / c#。 如果有不涉及正則表達式的簡單解決方案,我也很高興知道

真正讓我感到煩惱的是,我不能使用(.*?)來捕獲字符串,因為看起來非貪婪不適用於lookbehinds。

我也嘗試過: Regex.Split(str, @"\\]\\.\\[").Last().TrimEnd(']'); ,但我對這個解決方案也不是很滿意

以下應該可以解決問題。 假設字符串在最后一次匹配之后結束。

string input = "[abc].[some other string].[can.also.contain.periods].[our match]";

var search = new Regex("\\.\\[(.*?)\\]$", RegexOptions.RightToLeft);

string ourMatch = search.Match(input).Groups[1]);

假設您可以保證輸入格式,並且它只是您想要的最后一個條目,則可以使用LastIndexOf

string input = "[abc].[some other string].[can.also.contain.periods].[our match]";

int lastBracket = input.LastIndexOf("[");
string result = input.Substring(lastBracket + 1, input.Length - lastBracket - 2);

使用String.Split():

string input = "[abc].[some other string].[can.also.contain.periods].[our match]";
char[] seps = {'[',']','\\'};
string[] splitted = input.Split(seps,StringSplitOptions.RemoveEmptyEntries);

您在splitted [7]中獲得“不匹配”,並且can.also.contain.periods保留為一個字符串(splitted [4])

編輯:數組將在[]之后包含字符串。 依此類推,因此,如果組的數量可變,則可以使用它來獲取所需的值(或刪除只是“。”的字符串)。

編輯以將反斜杠添加到分隔符中,以處理“ \\ [abc \\]”之類的情況

Edit2:用於嵌套[]:

string input = @"[abc].[some other string].[can.also.contain.periods].[our [the] match]";
string[] seps2 = { "].["};
string[] splitted = input.Split(seps2, StringSplitOptions.RemoveEmptyEntries);

您在最后一個元素(索引3)中的[the]匹配項,則必須刪除多余的]

您有幾種選擇:

  • RegexOptions.RightToLeft是的,.NET正則表達式可以做到這一點! 用它!
  • 將所有內容與貪婪的前綴匹配,使用方括號捕獲您感興趣的后綴
    • 所以一般來說, pattern變成.*(pattern)
    • 在這種情況下, .*\\[([^\\]]*)\\] ,然后提取\\1捕獲的內容( 請參見rubular.com

參考文獻

暫無
暫無

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

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