检测并链接字符串中的Instagram



我正在寻找一种方法来链接包含以下内容的字符串...

Lorem ipsum, Lorem ipsom Instagram: @instausername Lorem ipsum

代码需要将此"Instagram: @instausername"放入此"<a href='https://www.instagram.com/@instausername'> Instagram: @instausername<a/>"中。 所以最终的字符串应该看起来像这样。

Lorem ipsum, Lorem ipsom <a href='https://www.instagram.com/@instausername'> Instagram: @instausername<a/> Lorem ipsum

我对正则表达式不是很熟悉,但我想它可以使用正则表达式解决,任何人都可以帮忙吗?

Instagram 用户名限制为 30 个字符,并且必须包含 只有字母、数字、句点和下划线。您不能包含 符号或其他标点符号作为用户名的一部分。

基于此,您可以使用:

string subjectString = "Lorem ipsum, Lorem ipsom Instagram: @instausername Lorem ipsum";
string resultString = null;
try {
resultString = Regex.Replace(subjectString, "Instagram: (@[^ ]+)", "<a href='https://www.instagram.com/$1'> Instagram: $1<a/>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
Console.WriteLine(resultString);
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}

Lorem ipsum, Lorem ipsom <a href='https://www.instagram.com/@instausername'> Instagram: @instausername<a/> Lorem ipsum

演示

最新更新