2015-05-04 111 views
2

我有文字這樣的:位置的長度和在正則表達式

這是一個示例{文本}。我想通知我的{Dada}我有一些 數據,{無用}。所以我需要以{{開頭並且以 }}結尾的數據。這些數據需要{找出}。

總括號中有一些子字符串在大括號內分開{}。我如何才能找到從{開始並以}結尾的子串的起始位置和長度?此外,我將用處理後的字符串替換子字符串。

+3

請在正則表達式的一些調查研究,制定一個嘗試,然後發佈您的代碼,如果你沒有得到你期待的結果。 – Shar1er80

+0

你有什麼嘗試?我們希望看到你已經嘗試過的東西,並幫助從那裏糾正 – blackmind

+0

*進一步,我將用處理後的字符串替換子字符串。*如果您分兩步執行(首先查找所有內容,然後全部替換),然後您將製作它非常複雜:每個替換都會移動所有找到的索引。 – xanatos

回答

2

隨着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 hereenter image description hereenter 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

+0

請讓我知道它是否適合您,或者您是否需要更多幫助。 –

+0

感謝它對我完美的作品。 – pcbabu

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; 
}