从介于两个字符串之间的字符串中检索字符串
本文关键字:字符串 检索 之间 于两个 | 更新日期: 2023-09-27 17:57:56
我有一个类似的字符串
"Hello i want to go."
我的代码给出"want to go."
但我需要" i "
和" to "
之间的字符串,我怎么能得到这个?我的代码如下。
string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];
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"之间的任何"word"。
编辑:已更改。。。to.*=>to ''s.*,如评论中所建议的。
string input = "Hello I want to go.";
string result = input.Split(" ")[2];
如果你想在"i"后面加单词,那么:
string result = input.Split(" i ")[1].Split(" ")[0];
使用
string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
只需使用一行简单的代码
var word = "Hello i want to go.".Split(' ')[2];
//返回单词"want"
string input = "Hello I want to go.";
string[] sentenceArray = input.Split(' ');
string required = sentenceArray[2];
这里有一个使用Regex的例子,它为您提供了每次出现"want"的索引:
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();
}
这里没有说Regex。。。
string result = input.Split.Skip(2).Take(1).First()
它的工作
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