从两个String之间的字符串中检索字符串?

时间:2013-02-05 07:08:03

标签: c# string design-patterns

我有一个像

的字符串
"Hello i want to go."

我的代码为"want to go." 但我需要" i "" to "之间的字符串,我怎么能得到这个?我的代码如下。

string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];

8 个答案:

答案 0 :(得分:3)

string input = "Hello i want to go.";
Regex regex = new Regex(@".*\s[Ii]{1}\s(\w*)\sto\s.*");
Match match = regex.Match(input);
string result = string.Empty;
if (match.Success)
{
    result = match.Groups[1].Value;
}

此正则表达式将匹配“i”(不区分大小写)和“to”之间的任何“单词”。

编辑:已更改...至。* =>按照评论中的建议去了\ s。*。

答案 1 :(得分:1)

string input = "Hello I want to go.";
string result = input.Split(" ")[2];

如果你想要“i”之后的单词,那么:

string result = input.Split(" i ")[1].Split(" ")[0];

答案 2 :(得分:0)

    string input = "Hello I want to go.";
    string[] sentenceArray = input.Split(' ');
    string required = sentenceArray[2];

答案 3 :(得分:0)

使用

string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor

答案 4 :(得分:0)

只需用一行简单的代码

即可
 var word = "Hello i want to go.".Split(' ')[2];

//返回单词“want”

答案 5 :(得分:0)

以下是使用Regex的示例,它为您提供每次“想要”的索引:

string str = "Hello i want to go. Hello i want to go. Hello i want to go.";
Match match = Regex.Match(str, "want");

while(match.Success){
    Console.WriteLine(string.Format("Index: {0}", match.Index));
    match = match.NextMatch();
}

答案 6 :(得分:0)

它没有说Regex ......

string result = input.Split.Skip(2).Take(1).First()

答案 7 :(得分:-1)

它的工作

public static string Between(this string src, string findfrom, string findto)
{
    int start = src.IndexOf(findfrom);
    int to = src.IndexOf(findto, start + findfrom.Length);
    if (start < 0 || to < 0) return "";
    string s = src.Substring(
                   start + findfrom.Length, 
                   to - start - findfrom.Length);
    return s;
}

可以称为

string respons = Between("Hello i want to go."," i "," to ");

它返回want