繁体   English   中英

如何使用通配符删除字符串的特定部分?

[英]How to remove a specific part of string with wildcard?

目前,我使用:

Variabls:

 int recordCount = 5;
 Header = "Index"; // Can also be "Starting Index"

标头:

 Header = Header.Split(' ')[0] + " (" + recordCount + ")";

变化:

 Index (5)

至:

 Index (6)

当我想用新的标题替换标题时,我使用上面的方法,但是问题是,当我开始在Header使用多个单词时,它将删除Header的其余部分。 即当它说Starting Index:它只显示Starting

我可以使用正则表达式简单地在括号之间查找值并将其替换为另一个变量吗?

Regex re = new Regex(@"\(\w+\)");
string input = "Starting Index: (12asd)";
string replacement = "12ddsa";
string result = re.Replace(input, replacement);

如果需要执行更复杂的替换(例如,替换取决于大括号之间的捕获值),则必须坚持使用Regex.Match方法

更新:随着Match事情很快变得丑陋:)

 Regex re = new Regex(@"^(.*)\((\w+)\)\s*$");
 string input = "Starting Index: (12)";
 var match = re.Match(input);

 string target = match.Groups[2].Value;
 //string replacement = target + "!!!!"; // general string operation
 int autoincremented = Convert.ToInt32(target) + 1; // if you want to autoincrement

 string result = String.Format("{0}: ({1})", match.Groups[1].Value, autoincremented);

如果您需要系统地替换其中一些(并且算法需要原始值),请记住Regex.Replace()可以接受将返回替换后值的方法。 这是一个示例,该示例将递增括号中包含的所有整数:

string s1 = "Index (5) and another (45) and still one more (17)";

string regex = @"\((\d+)\)";

string replaced = Regex.Replace(s1,regex,m => "("+(Convert.ToInt32(m.Groups[1].Value)+1).ToString()+")");
// Result: Index (6) and another (46) and still one more (18)

该方法接受一个正则表达式匹配对象,并返回一个替换字符串。 我在这里使用了lambda方法,但是您的正则表达式和替换方法可以根据需要分别设置。

您也可以这样:

string sample = "Index (5) Starting Index(0) and Length (6)";
string content = Regex.Replace(sample, @"(?<=\()\d+(?=\))", m => (int.Parse(m.Value) + 1).ToString());

此模式将查找用圆括号包裹的任意数量的数字,并将其前进到1。

此处无需附加括号,因为它们在比赛中没有被捕获。

您可以使用此模式

\[\((\d+)\).*?\]

匹配括号之间的数字,然后您可以用所需的数字替换该数字

var mg = Regex.Match( "Starting Index:(10)", @"\[\((\d+)\).*?\]");

if (mg.Success)
{
    var num = mg.Groups[1].Value; // num == 10
}

之后

headerString = headerString.Replace("10", "11");

\\((\\d+)\\)这将更适合

并在这种情况下将替换数字“ asdq(wdq)wdqwd(12)”

int dynamicNumber = 6;

string pattern = string.Format("({0})", dynamicNumber);

string data = "My Header 6:";

Console.WriteLine (Regex.Replace(data,pattern, "!!!")); // My Header !!!:

暂无
暂无

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

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