我正在尝试从电子邮件中提取内容。电子邮件的一般格式始终为:
blablablablabllabla hello my friend.
[what I want]
Goodbye my friend blablablabla
现在我做了:
string.LastIndexOf("hello my friend");
string.IndexOf("Goodbye my friend");
这会在它开始之前给我一点,并在它开始之后给出一个点。我可以使用什么方法?我找到了:
String.Substring(Int32, Int32)
但这只是起始位置。
我可以使用什么?
答案 0 :(得分:25)
Substring采用起始索引(从零开始)和要复制的字符数。
你需要做一些数学运算,如下:
string email = "Bla bla hello my friend THIS IS THE STUFF I WANTGoodbye my friend";
int startPos = email.LastIndexOf("hello my friend") + "hello my friend".Length + 1;
int length = email.IndexOf("Goodbye my friend") - startPos;
string sub = email.Substring(startPos, length);
您可能希望将字符串常量放在const string
。
答案 1 :(得分:8)
您也可以使用Regex
string s = Regex.Match(yourinput,
@"hello my friend(.+)Goodbye my friend",
RegexOptions.Singleline)
.Groups[1].Value;
答案 2 :(得分:2)
您可以简单地计算从开始和结束的长度
const string startText = "hello my friend";
var start = str.LastIndexOf(startText) + startText.Length;
var end = str.IndexOf("Goodbye my friend");
var length = end -start;
str.Substring(start,length);
答案 3 :(得分:1)
string s1 = "find a string between within a lengthy string";
string s2 = s1.IndexOf("between").ToString();
string output = s1.Substring(0, int.Parse(s2));
Console.WriteLine("string before between is : {0}", output);
Console.ReadKey();
答案 4 :(得分:-2)
尝试myStr.substring(start,end);