Если вы используете язык .NET, то вы могли бы сделать это более надежно, чем только с помощью регулярных выражений, чтобы попытаться получить значение. HtmlAgilityPack хорош для анализа HTML, даже если HTML немного искажен.
Здесь у меня есть функция, которая пытается извлечь атрибут href первого элемента в куске HTML, а затем остальная часть программы показывает два способа извлечь часть href после "/ wiki /" :
Option Infer On
Imports System.Text.RegularExpressions
Imports HtmlAgilityPack
Module Module1
''' <summary>
''' Get the value of the href attribute in the first anchor (<a>) element of (a fragment of) an HTML string.
''' </summary>
''' <param name="s">An HTML fragment.</param>
''' <returns>The value of the href attribute in the first anchor (<a>) element.</returns>
''' <remarks>Throws a FormatException if the href value cannot be found.</remarks>
Function GetHref(s As String) As String
' Get the value of the href attribute, if it exists, in a reliable fashion. '
Dim htmlDoc As New HtmlDocument
htmlDoc.LoadHtml(s)
Dim link = htmlDoc.DocumentNode.SelectSingleNode("//a")
Dim hrefValue = String.Empty
If link IsNot Nothing Then
If link.Attributes("href") IsNot Nothing Then
hrefValue = link.Attributes("href").Value
Else
' there was no href '
Throw New FormatException("No href attribute in the <a> element.")
End If
Else
' there was no <a> element '
Throw New FormatException("No <a> element.")
End If
Return hrefValue
End Function
Sub Main()
Dim s = "<li><a href=""/wiki/%E1%83%90%E1%83%90%E1%83%92%E1%83%94%E1%83%91%E1%83%A1"" title=""ააგებს"">ააგებს</a></li>"
Dim dataToCapture = String.Empty
Dim hrefValue = GetHref(s)
' OPTION 1 - using RegEx
' Only get a specific pattern of characters
Dim re = New Regex("^/wiki/((?:%[0-9A-F]{2})+)", RegexOptions.IgnoreCase)
Dim m = re.Match(hrefValue)
If m.Success Then
dataToCapture = m.Groups(1).Value
Console.WriteLine(dataToCapture)
Else
Console.WriteLine("Failed to match with RegEx.")
End If
' OPTION 2 - looking at the string
' Just get whatever comes after the required start of the href value.
Dim mustStartWith = "/wiki/"
If hrefValue.StartsWith(mustStartWith) Then
dataToCapture = hrefValue.Substring(mustStartWith.Length)
Console.WriteLine(dataToCapture)
Else
Console.WriteLine("Nothing found with string operations.")
End If
' the percent-encoded data could be decoded with System.Uri.UnescapeDataString(dataToCapture) '
Console.ReadLine()
End Sub
End Module
в регулярном выражении, круглые скобки, т.е. ()
, указывают на группу захвата. Тем не менее, нам не нужно фиксировать отдельные части %AA
, поэтому у них есть модификатор ?:
, чтобы указать, что они не захватываются групп.
(Ложные «s только, чтобы помочь SO цвет код правильно.)
Кажется, что не работает. Я использую re library в python 2.7. – osk