Quelqu'un at-il un bon code C# (et des expressions régulières) qui va analyser une chaîne et "linkify" toutes les URLs qui peuvent être dans la chaîne?Code C# pour lier les URL dans une chaîne
Répondre
Il est une tâche assez simple, vous pouvez acheive avec Regex et un prêt-à-go expression régulière de:
Quelque chose comme:
var html = Regex.Replace(html, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+" +
"\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?" +
"([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$",
"<a href=\"$1\">$1</a>");
Vous peut également être intéressé non seulement par la création de liens, mais aussi par le raccourcissement d'URL. Voici un bon article sur ce sujet:
Voir aussi:
- Regular Expression Workbench à MSDN
- Converting a URL into a Link in C# Using Regular Expressions
- Regex to find URL within text and make them as link
- Regex.Replace Method à MSDN
- The Problem With URLs par Jeff Atwood
- Parsing URLs with Regular Expressions and the Regex Object
- Format URLs in string to HTML Links in C#
- Automatically hyperlink URL and Email in ASP.NET Pages with C#
Bonjour. Bonne réponse. La plupart des suggestions dans votre message (et liens) semblent fonctionner mais elles semblent toutes casser n'importe quels liens existants dans le texte évalué. –
VSvous pouvez essayer différentes expressions reg de regixlib.com et trouver celle qui vous convient le mieux. –
@VSmith: Voulez-vous dire que vous avez une chaîne comme "bonjour there, voir: http://www.b.com"; et vous voulez seulement relier le second? –
Il est pas si facile que vous pouvez lire dans ce blog post by Jeff Atwood. Il est particulièrement difficile de détecter la fin d'une URL.
Par exemple, est la partie entre parenthèses de fin de l'URL ou non:
- http : //en.wikipedia.org/wiki/PCTools (CentralPointSoftware)
- une URL entre parenthèses (http : //en.wikipedia.org) plus de texte
Dans le premier cas, les parenthèses font partie de l'URL. Dans le second cas, ils ne le sont pas!
Et comme vous pouvez le voir à partir des URLs linkées dans cette réponse, tout le monde ne le comprend pas correctement :) – Ray
Eh bien, en fait, je ne voulais pas que les deux URL soient liées. Mais il semble que ce n'est pas pris en charge. – M4N
L'expression rationnelle de Jeff semble mal afficher dans mon navigateur, je crois que cela devrait être: "\ (? \ Bhttp: // [-A-Za-z0-9 + & @ # /%? = ~ _() | !: ,.;] * [- A-Za-z0-9 + & @ # /% = ~ _() |] " –
protected string Linkify(string SearchText) {
// this will find links like:
// http://www.mysite.com
// as well as any links with other characters directly in front of it like:
// href="http://www.mysite.com"
// you can then use your own logic to determine which links to linkify
Regex regx = new Regex(@"\b(((\S+)?)(@|mailto\:|(news|(ht|f)tp(s?))\://)\S+)\b", RegexOptions.IgnoreCase);
SearchText = SearchText.Replace(" ", " ");
MatchCollection matches = regx.Matches(SearchText);
foreach (Match match in matches) {
if (match.Value.StartsWith("http")) { // if it starts with anything else then dont linkify -- may already be linked!
SearchText = SearchText.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
}
}
return SearchText;
}
Bravo pour poster celui-là :) –
Nous avons fini par utiliser quelque chose de très similaire, avec une modification. Nous avons fini par nous assurer que le remplacement ne se produit qu'une seule fois. Cela signifie que nous allons manquer certains liens (liens qui se produisent plus d'une fois) mais supprime la possibilité de liens tronqués dans deux cas: 1) Quand il y a deux liens où l'un est plus détaillé que l'autre. par exemple. "http://google.com http://google.com/reader" 2) Lorsqu'il existe un mélange de liens HTML avec des liens en texte brut. par exemple. "Http://google.com Google" si (input.IndexOf (match.Value) == input.LastIndexOf (match.Value)) { ...} –
bien, après beaucoup de recherches sur ce sujet, et plusieurs tentatives de fixer des moments où
- personnes entrent dans http://www.sitename.com et www.sitename.com dans le même poste
- fixe à parenthisis comme (http://www.sitename.com) et http://msdn.microsoft.com/en-us/library/aa752574(vs.85).aspx
- longues urls comme: http://www.amazon.com/gp/product/b000ads62g/ref=s9_simz_gw_s3_p74_t1?pf_rd_m=atvpdkikx0der&pf_rd_s=center-2&pf_rd_r=04eezfszazqzs8xfm9yd&pf_rd_t=101&pf_rd_p=470938631&pf_rd_i=507846
nous utilisons maintenant cette extension HtmlHelper ...Je pensais partager et obtenir des commentaires:
private static Regex regExHttpLinks = new Regex(@"(?<=\()\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|](?=\))|(?<=(?<wrap>[=~|_#]))\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|](?=\k<wrap>)|\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static string Format(this HtmlHelper htmlHelper, string html)
{
if (string.IsNullOrEmpty(html))
{
return html;
}
html = htmlHelper.Encode(html);
html = html.Replace(Environment.NewLine, "<br />");
// replace periods on numeric values that appear to be valid domain names
var periodReplacement = "[[[replace:period]]]";
html = Regex.Replace(html, @"(?<=\d)\.(?=\d)", periodReplacement);
// create links for matches
var linkMatches = regExHttpLinks.Matches(html);
for (int i = 0; i < linkMatches.Count; i++)
{
var temp = linkMatches[i].ToString();
if (!temp.Contains("://"))
{
temp = "http://" + temp;
}
html = html.Replace(linkMatches[i].ToString(), String.Format("<a href=\"{0}\" title=\"{0}\">{1}</a>", temp.Replace(".", periodReplacement).ToLower(), linkMatches[i].ToString().Replace(".", periodReplacement)));
}
// Clear out period replacement
html = html.Replace(periodReplacement, ".");
return html;
}
ont trouvé l'expression suivante régulière http://daringfireball.net/2010/07/improved_regex_for_matching_urls
me semble très bon. La solution de Jeff Atwood ne gère pas beaucoup de cas. josefresno me semblent gérer tous les cas. Mais quand j'ai essayé de le comprendre (en cas de demande de soutien) mon cerveau était bouilli.
Il est classe:
public class TextLink
{
#region Properties
public const string BeginPattern = "((http|https)://)?(www.)?";
public const string MiddlePattern = @"([a-z0-9\-]*\.)+[a-z]+(:[0-9]+)?";
public const string EndPattern = @"(/\S*)?";
public static string Pattern { get { return BeginPattern + MiddlePattern + EndPattern; } }
public static string ExactPattern { get { return string.Format("^{0}$", Pattern); } }
public string OriginalInput { get; private set; }
public bool Valid { get; private set; }
private bool _isHttps;
private string _readyLink;
#endregion
#region Constructor
public TextLink(string input)
{
this.OriginalInput = input;
var text = Regex.Replace(input, @"(^\s)|(\s$)", "", RegexOptions.IgnoreCase);
Valid = Regex.IsMatch(text, ExactPattern);
if (Valid)
{
_isHttps = Regex.IsMatch(text, "^https:", RegexOptions.IgnoreCase);
// clear begin:
_readyLink = Regex.Replace(text, BeginPattern, "", RegexOptions.IgnoreCase);
// HTTPS
if (_isHttps)
{
_readyLink = "https://www." + _readyLink;
}
// Default
else
{
_readyLink = "http://www." + _readyLink;
}
}
}
#endregion
#region Methods
public override string ToString()
{
return _readyLink;
}
#endregion
}
utiliser dans cette méthode:
public static string ReplaceUrls(string input)
{
var result = Regex.Replace(input.ToSafeString(), TextLink.Pattern, match =>
{
var textLink = new TextLink(match.Value);
return textLink.Valid ?
string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", textLink, textLink.OriginalInput) :
textLink.OriginalInput;
});
return result;
}
cas de test:
[TestMethod]
public void RegexUtil_TextLink_Parsing()
{
Assert.IsTrue(new TextLink("smthing.com").Valid);
Assert.IsTrue(new TextLink("www.smthing.com/").Valid);
Assert.IsTrue(new TextLink("http://smthing.com").Valid);
Assert.IsTrue(new TextLink("http://www.smthing.com").Valid);
Assert.IsTrue(new TextLink("http://www.smthing.com/").Valid);
Assert.IsTrue(new TextLink("http://www.smthing.com/publisher").Valid);
// port
Assert.IsTrue(new TextLink("http://www.smthing.com:80").Valid);
Assert.IsTrue(new TextLink("http://www.smthing.com:80/").Valid);
// https
Assert.IsTrue(new TextLink("https://smthing.com").Valid);
Assert.IsFalse(new TextLink("").Valid);
Assert.IsFalse(new TextLink("smthing.com.").Valid);
Assert.IsFalse(new TextLink("smthing.com-").Valid);
}
[TestMethod]
public void RegexUtil_TextLink_ToString()
{
// default
Assert.AreEqual("http://www.smthing.com", new TextLink("smthing.com").ToString());
Assert.AreEqual("http://www.smthing.com", new TextLink("http://www.smthing.com").ToString());
Assert.AreEqual("http://www.smthing.com/", new TextLink("smthing.com/").ToString());
Assert.AreEqual("https://www.smthing.com", new TextLink("https://www.smthing.com").ToString());
}
Cela fonctionne bien, mais il correspond à des choses comme o.context, ou une autre chaîne qui a une période en eux. Serait bien de forcer .com/.org/.net etc, quelque part dans la chaîne –
Aussi, il force www, ce qui n'est pas toujours le cas. –
- 1. Convertir une chaîne en code C++
- 2. Analyser une chaîne URL dans Ruby
- 3. Comment lier une chaîne à doubler dans WPF?
- 4. Obtenir une URL à partir d'une chaîne
- 5. Comment lier "this" pour les rappels jQuery?
- 6. Le moyen le plus simple de convertir une URL en lien hypertexte dans une chaîne C#?
- 7. Comment lier une chaîne de ressources à Xaml dans Silverlight
- 8. Identifier si une URL est présente dans une chaîne
- 9. Comment lancer une URL dans monodevelop C#?
- 10. Comment lier statiquement des bibliothèques pour une ClassLibrary C#?
- 11. Comment analyser une URL en C?
- 12. Comment lier/grouper les surcharges dans les commentaires XML C#?
- 13. code Delphi pour aseptiser une URL saisie par l'utilisateur
- 14. Regex pour remplacer tout \ n dans une chaîne, mais pas ceux dans la balise [code] [/ code]
- 15. Citations en chaîne vbscript provoque une erreur url wsh invalide
- 16. Conversion d'ActionResult en chaîne URL dans une méthode statique
- 17. Vérification d'une chaîne pour les caractères corrects dans c
- 18. Comment utiliser ISAPI_rewrite pour convertir de jolies URL en URL de chaîne de requête?
- 19. Rechercher une phrase dans une chaîne (C#)
- 20. Comment lier une bibliothèque statique dans Visual C++ 2008?
- 21. mod_rewrite pour rediriger les URL commençant par une chaîne à google
- 22. Comment exécuter un code JavaScript dans une URL
- 23. Regex pour détecter Javascript Dans une chaîne
- 24. Comment écrire regex pour trouver un répertoire dans une URL?
- 25. Code C# le plus rapide pour télécharger une page Web
- 26. Supprimer les caractères d'une chaîne dans C
- 27. Créer un lien URL avec un ID pour une action
- 28. Comment faire pour éviter les guillemets doubles dans une chaîne?
- 29. UpdateModel dans asp.net MVC pour lier les tableaux?
- 30. c code pour les pages web dans rl-rtx
Cela semble être la question à la base d'une expression régulière canonique Solution. Peut-être que quelqu'un pourrait éditer le titre pour aider les chercheurs à le trouver? – JasonSmith