正则表达式替换一切,除了特定模式 [英] Regex replace everything except a particular pattern

查看:322
本文介绍了正则表达式替换一切,除了特定模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找解压:

50%

这是一个字符串,将有更多或更少的格式为:

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

50%是在这里的某个地方

我也想提取:

50%50 %25%

这是一个像这样的字符串:

From a string like this:

50的50%%为25%

Regex.Match()似乎是显而易见的竞争者。然而,这涉及到检查是否发现任何匹配(例如 match.Success )中,从阵列中的特定索引,和/或寻址出的风险提取结果-of界指数。

Regex.Match() seems the obvious contender. However, this involves checking if any matches were found (e.g. match.Success), extracting the results from a particular index in the array, and/or the risk of addressing an out-of-bounds index.

正则表达式替换一般是简单的应用。单行做工作,包括返回结果字符串。这是这么多的语言事实。

Regex replace is generally simpler to apply. A single line does the job, including returning the resulting string. This is true for so many languages.

结果= Regex.Replace(输入,stuffWeDontLike,)

基本上,我在寻找一个正则表达式过滤器 - 而不是输入的模式的替换的,我想进入该模式的检索

Basically, I am looking for a regex filter - instead of entering the pattern to replace, I want to enter the pattern to retrieve.

=百分比Regex.Filter(50%50%25%, [0-9] + \%)

我们可以形成一个正则表达式和反转的结果,就好像它是一个选择?这将允许使用正则表达式的替换。但是,我无法找到一个方法来方便反转正则表达式

Could we form a regex and invert the result, as if it were a selection? That would allow the use of regex replace. However, I could not find a way to easily invert a regex.

我们如何才能达到预期的效果(或类似;联接左右似乎是可以接受)非常短和简单的语法,与正则表达式替换?

How can we achieve the desired result (or similar; a join or so seems acceptable) with very short and simple syntax, similar to regex replace?

推荐答案

您可以使用 Regex.Matches 并串连各场比赛的结果。只需选择一个你最喜欢的。

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<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);
    }
}

这篇关于正则表达式替换一切,除了特定模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆