View Full Version : [Regex] Estrarre codice HTML all'interno di tag
Ciao a tutti,
sto creando un programma in C# che deve estrarre dati da pagine html in questo formato:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
<div id="title">
<!-- DATI -->
</div>
<div id="artist">
<!-- DATI -->
</div>
<div id="lyrics">
<!-- DATI -->
</div>
<div id="admin">
<!-- ROBA INUTILE -->
</div>
<div id="header">
<!-- ROBA INUTILE -->
</div>
</body>
</html>
Ok, mi servirebbero le regular expression per estrarre i dati contenuti dentro i div "title", "artist" e "lyrics" ...
Inoltre, qualcuno mi consiglia qualche testo semplice ed immediato per capire queste maledettissime regular expression, magari solo tramite esempi? Nella maggior parte dei casi con Google vengono fuori solo siti dove non si capisce (o meglio, dove non ci capisco) quasi nulla...
Grazie anticipatamente! :D
wingman87
29-09-2008, 17:35
Questo è un tutorial java sulle regex, ma il succo è lo stesso per tutti i linguaggi: LINK (http://java.sun.com/docs/books/tutorial/essential/regex/)
Per la regex che ti serve in particolare, prova questa, non sono sicuro che funzioni perché non sono molto pratico di queste cose:
<div id=""(title|artist|lyrics)"">(?<testoUtile>[\w\W]*?)</div>
Vincenzo1968
29-09-2008, 18:37
Con le regex è difficile gestire la cosa considerando che un tag potrebbe, per esempio, essere scritto anche su più righe.
Io utilizzerei un bell'automa a stati finiti:
File Prova.html :
<html>
<head>
</head>
<body>
<div id="title">
<!-- DATI -->
</div>
<div id="artist">
<!-- DATI -->
dati dell'artista
</div>
<div id="lyrics">
<!-- DATI -->
</div>
<div id="admin">
<!-- ROBA INUTILE -->
</div>
<div id="header">
<!-- ROBA INUTILE -->
</div>
</body>
</html>
http://www.guidealgoritmi.it/images/ImgForums/HtmlAutomaton.jpg
using System;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace HtmlAutomaton
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonFile_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBoxFile.Text = dlg.FileName;
}
}
private void buttonSearch_Click(object sender, EventArgs e)
{
string strFile = textBoxFile.Text.Trim();
string strDivID = textBoxID.Text.Trim();
textBoxContenuto.Text = "";
if (strFile.Length <= 0)
{
MessageBox.Show("Specificare il nome di un file, prego.");
buttonFile.Focus();
return;
}
if (strDivID.Length <= 0)
{
MessageBox.Show("Specificare l'ID della sezione DIV, prego.");
textBoxID.Focus();
return;
}
Automaton a = new Automaton(strFile);
textBoxContenuto.Text = a.ReadDivContent(strDivID);
}
}
public class Automaton
{
private string buffer = "";
private enum Stati {S_ERROR = -1, S0, S1, S2, S3, S4, S5, S6, S7, S8, S9}
public Automaton(string strFileName)
{
if (File.Exists(strFileName))
{
buffer = File.ReadAllText(strFileName);
}
else
{
buffer = "";
}
}
public string ReadDivContent(string divID)
{
Stati stato = Stati.S0;
string strContent = "Ciao Ciao";
StringBuilder sbContent = new StringBuilder();
StringBuilder sbTemp = new StringBuilder();
int k = 0;
while (k < buffer.Length)
{
switch (stato)
{
case Stati.S0:
if (buffer[k] == '<')
stato = Stati.S1;
break;
case Stati.S1:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S1;
}
else if (buffer[k] == 'd' || buffer[k] == 'D')
{
stato = Stati.S0;
if (k < buffer.Length - 2)
{
if (buffer[k + 1] == 'i' || buffer[k + 1] == 'I')
{
if (buffer[k + 2] == 'v' || buffer[k + 2] == 'V')
{
k += 2;
stato = Stati.S2;
}
}
}
}
else
{
stato = Stati.S0;
}
break;
case Stati.S2:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S3;
}
else
{
stato = Stati.S0;
}
break;
case Stati.S3:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S3;
}
else if (buffer[k] == 'i' || buffer[k] == 'I')
{
stato = Stati.S0;
if (k < buffer.Length - 1)
{
if (buffer[k + 1] == 'd' || buffer[k + 1] == 'D')
{
k++;
stato = Stati.S4;
}
}
}
break;
case Stati.S4:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S4;
}
else if (buffer[k] == '=')
{
stato = Stati.S5;
}
break;
case Stati.S5:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S4;
}
else if (buffer[k] == '"')
{
k++;
while (k < buffer.Length && buffer[k] != '"')
{
sbTemp.Append(buffer[k]);
k++;
}
if (sbTemp.ToString() == divID)
stato = Stati.S6;
else
stato = Stati.S0;
sbTemp.Remove(0, sbTemp.ToString().Length);
}
break;
case Stati.S6:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S6;
}
else if (buffer[k] == '>')
{
stato = Stati.S7;
}
break;
case Stati.S7:
while (k < buffer.Length)
{
if (buffer[k] != '<')
{
sbContent.Append(buffer[k]);
}
else
{
stato = Stati.S8;
break;
}
k++;
}
break;
case Stati.S8:
if (buffer[k] == '/')
{
k++;
while (k < buffer.Length && (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n'))
{
k++;
}
if (k < buffer.Length - 3)
{
if (buffer[k] == 'd' || buffer[k] == 'D')
{
if (buffer[k + 1] == 'i' || buffer[k + 1] == 'I')
{
if (buffer[k + 2] == 'v' || buffer[k + 2] == 'V')
{
k += 2;
stato = Stati.S9;
}
}
}
}
}
else
{
sbContent.Append('<');
sbContent.Append(buffer[k]);
stato = Stati.S7;
}
break;
case Stati.S9:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S9;
}
else if (buffer[k] == '>')
{
strContent = sbContent.ToString();
}
break;
}
k++;
}
return strContent;
}
}
}
Un bel sito sulle regex, con tanti esempi:
http://www.regular-expressions.info/
Vincenzo1968
30-09-2008, 15:38
C'è un piccolo errore nel codice che ho postato.
Codice errato:
...
case Stati.S5:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S4; // Qui l'errore: S4 va sostituito con S5
}
...
Codice corretto:
...
case Stati.S5:
if (buffer[k] == ' ' || buffer[k] == '\t' || buffer[k] == '\r' || buffer[k] == '\n')
{
stato = Stati.S5;
}
...
SnakePlissken
06-10-2008, 18:49
Con le regex è difficile gestire la cosa considerando che un tag potrebbe, per esempio, essere scritto anche su più righe.
Io utilizzerei un bell'automa a stati finiti:
Senza complicarsi inutilmente la vita con altre cose, in C# esce semplicemente così:
(devi usare System.Text.RegularExpressions)
public static string LeggiDati(string id)
{
Match m = Regex.Match(input, "<div\\s+id=\"" + id + "\"[^>]*>(?<dati>((?!</div>)(.|\\n))*)</div>");
return (m.Success ? m.Result("${dati}") : null);
}
Ti spiego brevemente la regex:
<div riconosce esattamente la stringa "<div"
\\s+ riconosce uno o più spazi (anche gli "a capo" sono spazi)
"id=\"" + id + "\"" corrisponde a id="title" o id="artist", ...
[^>]* riconosce zero o più caratteri diversi da '>'
> riconosce il carattere '>'
(?<dati>...) "cattura" il suo contenuto (i puntini ...) denominandolo "dati"
per quanto riguarda: ((?!</div>)(.|\\n))*
(.|\\n) riconosce un carattere che può essere:
- un carattere qualsiasi tranne l'"a capo"
- l'"a capo"
cioè riconosce un carattere qualsiasi.
(.|\\n)* riconosce zero p più caratteri qualsiasi
((?!</div>)(.|\\n))* impone il vincolo "(?!</div>)" che per ciascun
carattere riconosciuto, esso sia tale che la parte di stringa
che da esso inizia non coincida con "</div>"
</div> riconosce esattamente la stringa "</div>"
Infine, siccome ti cattura anche degli spazi iniziali e finali, usa la string.Trim() per cancellarli (questo poteva essere fatto anche a livello di Regex ma poi rischiava di risultare un tantino oscuro il pattern).
Per inciso, puoi sempre usare le Regex per eliminare gli spazi multipli o sostituire gli \n e \r con semplici spazi (cosa che in genere va fatta nella traduzione Html --> stringa):
nuovaStringa = Regex.Replace(vecchiaStringa, "((\\s{2,})|\\n|\\r)", " ");
E similmente con Regex puoi sostituire i tag <br> con \n.
Spero di esserti stato utile!
Ciao! :D
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.