0

次の文字列があります。

This isMyTest testing

結果としてisMyTestを取得したい。最初の 2 文字しか使用できません ("is")。単語の残りの部分は異なる場合があります。

基本的に、chk で始まるスペースで区切られた最初の単語を選択する必要があります。

私は次のことから始めました:

if (text.contains(" is"))
{
text.LastIndexOf(" is"); //Should give me index.
}

次のようなものに一致させる必要があるため、単語の正しい境界を見つけることができません

4

3 に答える 3

3

正規表現を使用できます。

    文字列パターン=@"\ bis";
    string input="これはMyTestテストです";
    Regex.Matches(input、pattern);を返します。

于 2012-09-20T22:46:15.607 に答える
1

正規表現の一致を使用するのはどうですか?一般に、文字列内のパターンを検索する場合(つまり、スペースで始まり、他の文字が続く場合)、正規表現はこれに完全に適しています。正規表現ステートメントは、実際にはコンテキストに依存する領域(HTMLなど)でのみ分解されますが、通常の文字列検索には最適です。

// First we see the input string.
string input = "/content/alternate-1.aspx";

// Here we call Regex.Match.
Match match = Regex.Match(input, @"[ ]is[A-z0-9]*",     RegexOptions.IgnoreCase);

// Here we check the Match instance.
if (match.Success)
{
    // Finally, we get the Group value and display it.
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
}
于 2012-09-20T22:31:58.733 に答える
1

IndexOfを使用して、次のスペースのインデックスを取得できます。

int startPosition = text.LastIndexOf(" is");
if (startPosition != -1)
{
    int endPosition = text.IndexOf(' ', startPosition + 1); // Find next space
    if (endPosition == -1)
       endPosition = text.Length - 1; // Select end if this is the last word?
}
于 2012-09-20T22:30:45.583 に答える