在A点和B点之间提取字符串的一部分

The*_*per 17 c# string

我试图从电子邮件中提取一些东西.电子邮件的一般格式始终是:

blablablablabllabla hello my friend.

[what I want]

Goodbye my friend blablablabla
Run Code Online (Sandbox Code Playgroud)

现在我做了:

                    string.LastIndexOf("hello my friend");
                    string.IndexOf("Goodbye my friend");
Run Code Online (Sandbox Code Playgroud)

这将在它开始之前给我一点,并在它开始之后给出一个点.我可以使用什么方法?我发现:

String.Substring(Int32, Int32)
Run Code Online (Sandbox Code Playgroud)

但这只占据了起始位置.

我可以用什么?

Eri*_* J. 26

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);
Run Code Online (Sandbox Code Playgroud)

你可能想把字符串常量放在一个const string.

  • 是的,您确实需要添加它...除非您还希望在输出中显示“你好我的朋友”。试试看……我做到了。 (2认同)

L.B*_*L.B 10

你也可以使用正则表达式

string s =  Regex.Match(yourinput,
                        @"hello my friend(.+)Goodbye my friend", 
                        RegexOptions.Singleline)
            .Groups[1].Value;
Run Code Online (Sandbox Code Playgroud)