提取点A和B之间的字符串的一部分
我试图从电子邮件中提取某些内容。电子邮件的一般格式将永远是:提取点A和B之间的字符串的一部分
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)
但这只需要起始位置。
我能用什么?
子串取开始索引(从零开始)和你想要的字符数要复制。
你需要做一些数学,就像这样:
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
。
嗨,谢谢,这将工作。但是,不需要在LastIndexOf方法之后添加字符串,因为这会为您提供最后一个位置。干杯。 – TheGateKeeper 2012-02-29 19:39:17
是的,你需要添加它......除非你还想在输出中输入“你好我的朋友”。尝试一下...我做到了。 – 2012-02-29 19:44:02
你说得对,但为什么会发生? email.LastIndexOf(“你好我的朋友”)这不会给“朋友”后的字符的索引? – TheGateKeeper 2012-02-29 19:47:42
尝试myStr.substring(start,end);
什么?我只是在问题中列出了这一点。该方法采用开始和长度,而不是开始和结束。 – TheGateKeeper 2012-02-29 19:36:23
from [docs](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html): substring(int beginIndex,int endIndex) 返回一个新的字符串那是这个字符串的一个子字符串。 我以为你在谈论一个来自String的静态函数,而不是实例方法,对不起。 – 2012-02-29 19:39:04
Np队友,无论如何。 – TheGateKeeper 2012-02-29 19:46:26
你也可以使用正则表达式
string s = Regex.Match(yourinput,
@"hello my friend(.+)Goodbye my friend",
RegexOptions.Singleline)
.Groups[1].Value;
与直接字符串操作相比,RegEx可能非常慢。不知道它是否对OP有影响。 – 2012-02-29 19:37:54
从未成为正则表达式的粉丝......主要是因为我不知道如何使用它。你能解释一下forumla的工作原理吗? – TheGateKeeper 2012-02-29 19:38:02
@TheGateKeeper它发现'你好我的朋友'和'再见我的朋友'之间的所有字符'(。+)'。 Paranthesis是为了得到匹配的字符组[1](不是整个字符串你好.......朋友) – 2012-02-29 19:40:11
你可以简单地计算从开始的长度和结束
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);
你也需要考虑“你好我的朋友”的长度。您的代码也将抓住该标记词组。 – 2012-02-29 19:42:26
谢谢,类似于第一个答案。 – TheGateKeeper 2012-02-29 20:09:14
@Eric是的得到了正确 – 2012-02-29 20:29:25
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();
如果电子邮件与“再见我的朋友”开始,以“你好我的朋友”或什么都没有结束,会发生什么?你确定这是一种可行的方法吗? – 2012-02-29 19:38:20
是的,我确定这是一封自动发送的电子邮件。它会一直这样发送。另外我的程序将从定义文件中读取,我总是可以更改字符串。 – TheGateKeeper 2012-02-29 19:44:57