0

I have the following string:

This isMyTest testing

I want to get isMyTest as a result. I only have two first characters available("is"). The rest of the word can vary.

Basically, I need to select a first word delimeted by spaces which starts with chk.

I've started with the following:

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

now I cannot find the right bound of the word since I need to match on something like

3 Answers 3

3

You can use regular expressions:

    string pattern = @"\bis";
    string input = "This isMyTest testing";
    return Regex.Matches(input, pattern);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use IndexOf to get the index of the next space:

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

Comments

1

What about using a regex match? Generally if you are searching for a pattern in a string (ie starting with a space followed by some other character) regex are perfectly suited to this. Regex statements really only fall apart in contextually sensitive areas (such as HTML) but are perfect for a regular string search.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.