5

以下のようなテキストがあるとします。

string str = @"stackoverflow(積み重ねる:stackoverflow)overstackflow(_:stackoverflow)";

大胆なフィールドを取得したい。テキスト内の "(" と ":" を見つけて、それらの間のテキストを取得する必要があると思います。

何かアドバイス?

4

5 に答える 5

6

おそらく単純な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);
}

デモ

于 2012-12-20T09:23:15.763 に答える
1
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

デモ

于 2012-12-20T09:25:03.060 に答える
1

この投稿を見て、答えを見つけることができます。

括弧 (丸括弧) の間にあるテキストを抽出するにはどうすればよいですか?

その正規表現に小さな変更を加えるだけで済みます。

于 2012-12-20T09:19:47.937 に答える
1
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
  }
}
于 2012-12-20T09:20:05.763 に答える
1

私は次のようなものに行きます:

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);
}
于 2012-12-20T09:21:25.413 に答える