Regex replace everything except a particular pattern

前端 未结 3 1601
我在风中等你
我在风中等你 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:39

    One solution is to use regex replace as follows:

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

    Output:

    50%50%25%

    As a general approach:

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

    This finds anything that matches either of the following:

    • The pattern. Captured as $1. This is what we want to keep.
    • Any character, any number of times, but non-greedy. This finds anything that is not captured by the first group. ?: because we don't need to capture this group.

    As MSDN states: "$1 replaces the entire match with the first captured subexpression." (That is, all matches for that substring, concatenated.)

    Effectively, this is the described regex filter.

提交回复
热议问题