尝试从长字符串中取出网址

时间:2020-01-21 11:22:51

标签: c# string substring indexof

我有一个很长的文本字符串,已经从sql表中隔离出来并变成了字符串;

CreateUserCommand(IOptionsSnapshot<MyOpts> opts)

我现在正试图仅取出URL并将其放入另一个字符串中。我需要从“ http”中获取它,并在唯一ID后面的空格处结束它。

我尝试过:

Thank you for your request. Please click the following link to reset your password: http://localhost:5692/Public/LogonSetPassword.aspx?activationLinkId=603fa657-9460-4417-adc2-7bcad0416c3e If clicking on the link does not work then please copy and paste it directly into your browser address bar

但是它似乎不起作用。 有人可以解释我哪里出问题了吗? 谢谢。

5 个答案:

答案 0 :(得分:1)

URL可以包含许多字符,但不能包含空格,因此使用regex可能会更成功。

一个简单的模式将显示为“以http开头,后跟一个以上的非空白字符”

var regex = new Regex(@"http[^\s]+");
Console.WriteLine(regex.Match(sql));

实时示例:https://rextester.com/BOV71354

答案 1 :(得分:1)

您尝试使用sql.IndexOf(" ")匹配第一个出现的空格,在您的示例中,该空格位于索引5(在Thank you中)。

您必须在第一次出现http之后之后,先寻找新行的第一次出现:

var startIndex = sql.IndexOf("http", StringComparison.Ordinal);
var endIndex = sql.IndexOf('\r', startIndex); // maybe '\n' or ' '

并且Substring的第二个参数是长度而不是索引,正确的代码是:

var url = sql.Substring(startIndex, endIndex - startIndex - 1);

但是最干净的方法是使用regexp

// Assuming there is only one url and it fit alone on a single line.
var regex = new Regex(@"^http.*\r?$", RegexOptions.Multiline);
var match = regex.Match(s);
if (match.Success)
{
    var url = match.Value;
}

答案 2 :(得分:0)

此解决方案假定只有一个网址

var indexOfHttp = sql.IndexOf("http");
var strStartingFromHttp = sql.Substring(indexOfHttp);
var activationUrl = strStartingFromHttp.Substring(0 , strStartingFromHttp.IndexOf('\n'));

https://dotnetfiddle.net/tnUTPk

答案 3 :(得分:0)

我不能完全确定您所说的网址是什么。 您使用的代码将从全文中第一个找到的“ http”实例开始,然后转到字符串中“”的第一个索引。 “ http”的第一个实例在第三行,“”的第一个实例在“谢谢”之后的第一行。

如果该网址始终总是在单独的一行上,并且您只有一个网址,则可以简单地用新行将字符串分开,然后检查该行是否以http:开头。

string url = null;
foreach (string line in sql.Split('\n'))
{
    if (line.ToLower().StartsWith("http"))
    {
        url = line;
        break;
    }
}
if (url != null) //You found a url

在这种情况下,“ url”将为“ http://localhost:5692/Public/LogonSetPassword.aspx?activationLinkId=603fa657-9460-4417-adc2-7bcad0416c3e

答案 4 :(得分:0)

var regex = new Regex(@"https?://(www.)?[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)", RegexOptions.Compiled);
var activationUrl = regex.Match(sql)?.Value;

https://dotnetfiddle.net/Cz16QR