string text = "{hello|{hi}} {world}";
実際には、指定された文字列から「{」と「}」の各出現位置が必要です
助けてください...よろしくお願いします!
Regex.Matches を使用できます。「|」で区切られたすべての文字列を検索します。文中。すべての文字列をインデックスとともに Dictioanry に追加できます。
string pattern = "{|}";
string text = "{hello|{hi}} {world}";
Dictionary<int, string> indeces = new Dictionary<int, string>();
foreach (Match match in Regex.Matches(text, pattern))
{
indeces.Add(match.Index, match.Value);
}
結果は次のとおりです。
0-{
7-{
10-}
11-}
13-{
19-}
文字をループする関数を作成する正規表現を使用できます
例 1
string text = "{hello|{hi}} {world}";
var indexes = new List<int>();
var ItemRegex = new Regex("[{}]", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(text))
{
indexes.Add(ItemMatch.Index);
}
例 2 (linq の方法)
string text = "{hello|{hi}} {world}";
var itemRegex = new Regex("[{}]", RegexOptions.Compiled);
var matches = itemRegex.Matches(text).Cast<Match>();
var indexes = matches.Select(i => i.Index);
var str = "{hello|{hi}} {world}";
var indexes = str.ToCharArray()
.Select((x,index) => new {x, index})
.Where(i => i.x=='{' ||i.x=='}')
.Select(p=>p.index);
結果
0
7
10
11
13
19
2 つのリストを作成する
List<int> opening
List<int> closing
次に、文字列をスキャンして int i = 0; を探します。i < string.length -1;i++. 各文字を開き括弧または閉じ括弧と比較します。if chr == '{' のように、カウンター i を対応するリストに入れます。
文字列全体の後 対応するリストに、開き括弧と閉じ括弧の位置が必要です。
それは役に立ちましたか?
発生を列挙できます。
public static IEnumerable<int> FindOccurences(String value, params Char[] toFind) {
if ((!String.IsNullOrEmpty(value)) && (!Object.ReferenceEquals(null, toFind)))
for (int i = 0; i < value.Length; ++i)
if (toFind.Contains(value[i]))
yield return i;
}
...
String text = "{hello|{hi}} {world}";
foreach(int index in FindOccurences(text, '{', '}')) {
...
}