我知道如何使用Regex.Split()和Regex.Replace();但不是在更换时如何保留某些数据。
如果我在String []中有以下几行文本(在每个之后拆分;)
“
using system;
using system.blab;
using system.blab.blabity;
“
我将如何循环播放并将所有'using'替换为'',但使用(。+;)'匹配整行''。 并最终得到以下(但不仅仅是Regex.replace(“使用”,“”);) “
<using> system;
<using> system.blab;
<using> system.blab.blabity;
“
答案 0 :(得分:3)
如果str是你当前的字符串,那么
string str = @"using system;
using system.blab;
using system.blab.blabity;";
str = str.Replace("using ", "<using> ");
答案 1 :(得分:2)
在Regex中使用parens指示引擎将该值存储为一个组。然后,当您调用Replace时,您可以使用$ n引用组,其中n是组的编号。我没有测试过这个,但是这样的话:
Regex.Replace(input, @"^using( .+;)$", "$1");
答案 2 :(得分:1)
这应该让你非常接近。您应该为要尝试匹配的每个逻辑项使用命名组。在这种情况下,您尝试匹配不是字符串“using”的所有内容。然后,您可以使用符号$ {yourGroupName}来引用替换字符串中的匹配项。我写了一个名为RegexPixie的工具,它会在您输入时显示您的内容的实时匹配,这样您就可以看到哪些有效,哪些无效。
//the named group has the name "everythingElse"
var regex = new Regex(@"using(?<everythingElse>[^\r\n]+)");
var content = new string [] { /* ... */ };
for(int i = 0; i < content[i]; i++)
{
content[i] = regex.Replace(content[i], "${everythingElse}");
}
答案 3 :(得分:0)
这结合了2个答案。它将word boundaries \b
包裹在using
周围,以执行仅整个单词搜索,然后在反向引用$1
string str = @"using system;
using system.blab;
using system.blab.blabity;";
str = Regex.Replace(str, @"\b(using)\b", "<$1>");