正则表达式中

时间:2015-05-04 13:27:12

标签: c# regex

我有这样的文字:

  

这是一个示例{text}。我想告诉我的{达达}我有一些   数据{无用}。所以我需要数据开始{并以...结束   }。这些数据需要{找出}。

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

2 个答案:

答案 0 :(得分:3)

使用Regex.Match,您可以通过访问Index属性检查每个匹配的索引,并通过检查Length属性来检查每个匹配的长度。

如果你想计算花括号,你可以使用\{(.*?)\}正则表达式,如下所示:

 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

答案 1 :(得分:1)

如果您知道您不会使用嵌套花括号,则可以使用以下内容:

var input = @"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 pattern = @"{[^]*}"
foreach (Match match in Regex.Matches(input, pattern)) {
    string subString = match.Groups(1).Value;
    int start = match.Groups(1).Index;
    int length = match.Groups(1).Length;
}