-1

我有一个字符串喜欢

"Hello i want to go."

我的代码给出"want to go." ,但我需要字符串," i "" to "怎样才能得到这个?我的代码如下。

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

8 回答 8

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”之间的任何“单词”。

编辑:按照评论中的建议将 ...to.* => 更改为 \s.* 。

于 2013-02-05T07:25:32.850 回答
1
string input = "Hello I want to go.";
string result = input.Split(" ")[2];

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

string result = input.Split(" i ")[1].Split(" ")[0];
于 2013-02-05T07:10:59.407 回答
0
    string input = "Hello I want to go.";
    string[] sentenceArray = input.Split(' ');
    string required = sentenceArray[2];
于 2013-02-05T07:11:59.073 回答
0

采用

string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
于 2013-02-05T07:13:37.823 回答
0

只需一行简单的代码即可

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

//返回单词“want”

于 2013-02-05T07:16:14.603 回答
0

这是一个使用正则表达式的示例,它为您提供每次出现“想要”的索引:

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();
}
于 2013-02-05T07:28:18.480 回答
0

没有地方说正则表达式...

string result = input.Split.Skip(2).Take(1).First()
于 2013-02-05T07:36:24.497 回答
-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

于 2013-02-05T08:29:10.193 回答