繁体   English   中英

C#Regex通配符多次替换

[英]C# Regex wildcard multiple replace

使用通配符搜索不同的字符串,例如搜索test0? (后面有一个空格? )。 搜索产生的字符串是:

test01 
test02 
test03 
(and so on)

替换文本应该是例如:

test0? - 

test0? -上面的通配符test0? - test0? -代表1,2或3 ......

所以,替换字符串应该是:

test01 - 
test02 - 
test03 - 

string pattern = WildcardToRegex(originalText);
fileName = Regex.Replace(originalText, pattern, replacementText);

public string WildcardToRegex(string pattern)
{
    return "^" + System.Text.RegularExpressions.Regex.Escape(pattern).
        Replace("\\*", ".*").Replace("\\?", ".") + "$";
}

问题是使用原始字符和添加的字符保存新字符串。 我可以搜索字符串并使用一些字符串操作保存原始文件,但这似乎是太多的开销。 必须有一个更简单的方法。

感谢您的任何意见。

编辑:

使用通配符搜索字符串? 可能的字符串是:
test01 someText
test02 someotherText
test03 moreText

使用Regex,搜索字符串模式将是:
TEST0? -
因此,每个字符串应该读取:
test01 - someText
test02 - someotherText
test03 - moreText

如何保留被正则表达式通配符替换的字符'?'

正如我的代码所示,它将作为测试出来? - someText
那是错的。

谢谢。

编辑编号2

首先,感谢大家的回答和指导。 它确实有帮助并引导我走上正轨,现在我可以更好地提出确切的问题:
它与替代有关。

在正则表达式后插入文本。

我给出的示例字符串,可能并不总是采用该格式。 我一直在寻找替代,但似乎无法使语法正确。 我正在使用VS 2008。

还有什么建议吗?

谢谢

如果你想用“test0? - ”替换“test0?”,你会写:

string bar = Regex.Replace(foo, "^test0. ", "$0- ");

这里的关键是$0 替换 ,它将包括匹配的文本。

因此,如果我正确理解您的问题,您只需要将replacementText设置为"$0- "

如果我正确理解了这个问题,你不能只使用匹配吗?

//Convert pattern to regex (I'm assuming this can be done with your "originalText")
Regex regex = pattern;

//For each  match, replace the found pattern with the original value + " -"
foreach (Match m in regex.Matches)
{
    RegEx.Replace(pattern, m.Groups[0].Value + " -");
}

所以我不是100%清楚你正在做什么,但我会试一试。

我假设您要使用“文件通配符”( ? / * )并搜索一组匹配的值(同时保留使用占位符本身存储的值),然后将其替换为新值(重新插入这些占位符)。 考虑到这一点,并且可能有很多矫枉过正(因为你的要求有点奇怪),这就是我想出来的:

// Helper function to turn the file search pattern in to a
// regex pattern.
private Regex BuildRegexFromPattern(String input)
{
    String pattern = String.Concat(input.ToCharArray().Select(i => {
        String c = i.ToString();
        return c == "?" ? "(.)"
            : c == "*" ? "(.*)"
            : c == " " ? "\\s"
            : Regex.Escape(c);
    }));
    return new Regex(pattern);
}

// perform the actual replacement
private IEnumerable<String> ReplaceUsingPattern(IEnumerable<String> items, String searchPattern, String replacementPattern)
{
    Regex searchRe = BuildRegexFromPattern(searchPattern);

    return items.Where(s => searchRe.IsMatch(s)).Select (s => {
        Match match = searchRe.Match(s);
        Int32 m = 1;
        return String.Concat(replacementPattern.ToCharArray().Select(i => {
            String c = i.ToString();
            if (m > match.Groups.Count)
            {
                throw new InvalidOperationException("Replacement placeholders exceeds locator placeholders.");
            }
            return c == "?" ? match.Groups[m++].Value
                : c == "*" ? match.Groups[m++].Value
                : c;
        }));
    });
}

然后,在实践中:

String[] samples = new String[]{
    "foo01", "foo02 ", "foo 03",
    "bar0?", "bar0? ", "bar03 -",
    "test01 ", "test02 ", "test03 "
};

String searchTemplate = "test0? ";
String replaceTemplate = "test0? -";

var results = ReplaceUsingPattern(samples, searchTemplate, replaceTemplate);

从上面的samples列表中,我给出了:

matched:      & modified to:

test01         test01 -
test02         test02 -
test03         test03 -

但是,如果你真的想保存头痛,你应该使用替换参考。 没有必要重新发明轮子。 以上,有替换,可以改为:

Regex searchRe = new Regex("test0(.*)\s");
samples.Select(x => searchRe.Replace(s, "test0$1-"));

您可以捕获匹配字符串的任何部分并放置在替换语句中的任何位置,使用符号$后跟catched元素的索引(它从索引1开始)。

你可以用括号“()”来捕捉元素

例:

如果我有几个字符串与testXYZ,XYZ是一个3位数字,我需要用testZYX替换它,反转3位数,我会这样做:

string result = Regex.Replace(source, "test([0-9])([0-9])([0-9])", "test$3$2$1");

所以,在你的情况下,它可以做到:

string result = Regex.Replace(source, "test0([0-9]) ", "test0$1 - ");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM