从字符串中获取部分字符串

时间:2012-09-20 22:27:25

标签: c#

我有以下字符串:

This isMyTest testing

我希望得到isMyTest。我只有两个可用的第一个字符(“是”)。其余部分可能会有所不同。

基本上,我需要选择以chk开头的空格分隔的第一个单词。

我从以下开始:

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

现在我无法找到该单词的正确界限,因为我需要匹配类似

的内容

3 个答案:

答案 0 :(得分:3)

您可以使用正则表达式:


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

答案 1 :(得分: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?
}

答案 2 :(得分: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);
}