簡體   English   中英

正則表達式替換除特定模式以外的所有內容

[英]Regex replace everything except a particular pattern

我正在尋找提取:

50%

從具有或多或少此格式的字符串中:

The 50% is in here somewhere.

我還想提取:

50%50%25%

從這樣的字符串:

50% of 50% is 25%

Regex.Match()似乎是顯而易見的競爭者。 但是,這涉及檢查是否找到了任何匹配項(例如match.Success ),從數組中的特定索引中提取結果和/或存在越界索引的風險。

正則表達式替換通常更易於應用。 一行可以完成工作,包括返回結果字符串。 許多語言都是如此。

result = Regex.Replace(input, stuffWeDontLike, "")

基本上,我正在尋找一個正則表達式過濾器 -而不是輸入要替換的模式,而是要輸入要檢索的模式。

percentages = Regex.Filter("50% of 50% is 25%", "[0-9]+\\%")

我們可以形成一個正則表達式並反轉結果,就好像它是一個選擇一樣嗎? 那將允許使用正則表達式替換。 但是,我找不到輕松反轉正則表達式的方法。

我們如何用非常短而簡單的語法(類似於正則表達式替換)來達到所需的結果(或類似的結果;一個聯接還是可以接受的)?

您可以使用Regex.Matches並連接每個匹配結果。 只要選擇最喜歡的一個即可。

//Sadly, we can't extend the Regex class
public class RegExp
{
    //usage : RegExp.Filter("50% of 50% is 25%", @"[0-9]+\%")
    public static string Filter(string input, string pattern)
    {
        return Regex.Matches(input, pattern).Cast<Match>()
            .Aggregate(string.Empty, (a,m) => a += m.Value);
    }
}

public static class StringExtension
{
    //usage : "50% of 50% is 25%".Filter(@"[0-9]+\%")
    public static string Filter(this string input, string pattern)
    {
        return Regex.Matches(input, pattern).Cast<Match>()
            .Aggregate(string.Empty, (a,m) => a += m.Value);
    }
}

我不明白您為什么要使用replace的理由。 為什么要先走那條路? Regex類中的方法可以讓您精確地獲得所有所需的匹配項。 我找到的解決方案的round回方式毫無意義。

只需使用Matches()來收集匹配項。 然后,您可以將它們加入所需的字符串中。

var str = "50% of 50% is 25%";
var re = new Regex(@"\d+%");
var ms = re.Matches(str);
var values = ms.Cast<Match>().Select(m => m.Value);
var joined = String.Join("", values); // "50%50%25%"

一種解決方案是使用正則表達式替換,如下所示:

Regex.Replace("50% of 50% is 25%", "(\\d+\\%)|(?:.+?)", "$1");

輸出:

50%50%25%

作為一般方法:

Regex.Replace(input, (pattern)|(?:.+?), "$1");

這將找到與以下任何一項匹配的內容:

  • 模式。 捕獲為$1 這就是我們要保留的。
  • 任何字符,任何次數,但不貪心。 這將查找第一組捕獲的任何內容。 ?:因為我們不需要捕獲該組。

正如MSDN指出的那樣:“ $1用第一個捕獲的子表達式替換整個匹配項。” (也就是說,該子字符串的所有匹配項都是串聯的。)

實際上,這就是所描述的regex過濾器

暫無
暫無

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

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