gpt4 book ai didi

c# - 正则表达式中的位置和长度

转载 作者:行者123 更新时间:2023-11-30 20:43:53 25 4
gpt4 key购买 nike

我有这样的文字:

This is a sample {text}. I want to inform my {Dada} that I have some data which is {not useful}. So I need data to start by { and ends with }. This data needs to {find out}.

总文本有一些子字符串在花括号 {} 中分隔。如何找到以{开始并以}结束的子字符串的起始位置和长度?此外,我将用处理后的字符串替换子字符串。

最佳答案

Regex.Match ,您可以通过访问 Index 来检查每个匹配项的索引属性,以及每个匹配项的长度,方法是检查 Length属性(property)。

如果你想计算里面的大括号,你可以使用\{(.*?)\}正则表达式,像这样:

 var txt = "This is a sample {text}. I want to inform my {Dada} that I have some  data which is {not useful}. So I need data to start by { and ends with }. This data needs to {find out}.";
var rgx1 = new Regex(@"\{(.*?)\}");
var matchees = rgx1.Matches(txt);
// Get the 1st capure groups
var all_matches = matchees.Cast<Match>().Select(p => p.Groups[1].Value).ToList();
// Get the indexes of the matches
var idxs = matchees.Cast<Match>().Select(p => p.Index).ToList();
// Get the lengths of the matches
var lens = matchees.Cast<Match>().Select(p => p.Length).ToList();

输出:

enter image description here enter image description here enter image description here

也许,您会希望使用带有搜索和替换术语的字典,这样会更有效:

var dic = new Dictionary<string, string>();
dic.Add("old", "new");
var ttxt = "My {old} car";
// And then use the keys to replace with the values
var output = rgx1.Replace(ttxt, match => dic[match.Groups[1].Value]);

输出:

enter image description here

关于c# - 正则表达式中的位置和长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30031371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com