以下のようなテキストがあるとします。
string str = @"stackoverflow(
積み重ねる:stackoverflow)overstackflow(
_:stackoverflow)";
大胆なフィールドを取得したい。テキスト内の "(" と ":" を見つけて、それらの間のテキストを取得する必要があると思います。
何かアドバイス?
おそらく単純なstring
方法で:
IList<String> foundStrings = new List<String>();
int currentIndex = 0;
int index = str.IndexOf("(", currentIndex);
while(index != -1)
{
int start = index + "(".Length;
int colonIndex = str.IndexOf(":", start);
if (colonIndex != -1)
{
string nextFound = str.Substring(start, colonIndex - start);
foundStrings.Add(nextFound);
}
currentIndex = start;
index = str.IndexOf("(", currentIndex);
}
public static void Main(string[] args)
{
string str = @"stackoverflow(stack:stackoverflow)overstackflow(over:stackoverflow)";
Console.WriteLine(ExtractString(str));
}
static string ExtractString(string s)
{
var start = "(";
int startIndex = s.IndexOf(start) + start.Length;
int endIndex = s.IndexOf(":", startIndex);
return s.Substring(startIndex, endIndex - startIndex);
}
結果はですが、文字列を反復処理するためにループでstack
使用できます。foreach
string strRegex = @"\((.+?)\:";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"stackoverflow(stack:stackoverflow)overstackflow(over:stackoverflow)";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
私は次のようなものに行きます:
Regex matcher = new Regex(@"([^():}]+)\(([^():}]*):([^():}]*)\)");
MatchCollection matches = matcher.Matches(str);
これは、 のように見えるすべての入力を調べますgroup1(group2:group3)
。(いずれかのグループに , が含まれている場合、何がどこにあるの(
か)
を:
理解できないため、全体が無視されます。)
次に、一致した値を次のように取得できます
foreach(Match m in matches)
{
Console.WriteLine("First: {0}, Second: {1}, Third{2}",
m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value);
}
したがって、(
と の間のビットだけが必要な場合は、:
使用できます
foreach(Match m in matches)
{
Console.WriteLine(m.Groups[2].Value);
}