Regex replace everything except a particular pattern

前端 未结 3 1600
我在风中等你
我在风中等你 2021-01-22 12:44

I\'m looking to extract:

50%

From a string that will have more or less this format:

The 50% is in here somewhere.

I\'d

3条回答
  •  别那么骄傲
    2021-01-22 13:43

    You can use Regex.Matches and concatenate each matches result. Just pick one you like the most.

    //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()
                .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()
                .Aggregate(string.Empty, (a,m) => a += m.Value);
        }
    }
    

提交回复
热议问题