問題
您有一個具有重複模式的文本字符串。您希望將字符串中的一些數據提取到數據表中。字符串中的每個重複表示表中的一行。可能會有很多數據需要跳過,因為它不屬於表格。
解
使用JSL PatMatch 功能。您需要使用pat___函數來構建模式。以下示例生成在網頁上找到的鏈接數據表。
site = "https://en.wikipedia.org";
url = "/wiki/JMP_(statistical_software)";
html = Load Text File( site || url ); // Dec 2017: 200+ links here
quote = "\!""; // simplify escaping of quotation mark elsewhere
dt = New Table( url, New Column( "link", Character ), New Column( "text", Character ) );
// A typical link looks like this on Wikipedia:
//<A href="https://st.wikipedia.org/" lang="st" target="_blank" rel="nofollow noopener noreferrer">Sesotho</A>
// the following pattern will need tweaking for other sites.
rc = Pat Match( html, //
Pat Repeat( // until there are no more
Pat Break( "<" ) + // match up to, but not including, the <
(// either we've found a link with <A>> vlink + Pat Break( ">" ) // store match in vlink
// throw away the closing > then capture everything up to the
// closing </A>. this may include other tags
+ ">" + Pat Arb() >> vtext + "" + // store match in vtext
Pat Fence() + // fence off previously parsed data, back-up-and-retry is pointless
Pat Test( // inject some JSL into the match to save the results
If( Starts With( vlink, "#" ), // ignore in-page anchors
{} // nothing
, // else
If( Starts With( vlink, "/" ), // within site links begin with /
vlink = site || vlink; // fully qualified
);
dt << addrows( 1 ); // extend the table by one row
dt:link = vlink; // vlink and vtext are the JSL variables
dt:text = vtext; // link and text are the table variables
); //
1; // PatTest needs a true result to keep going
) //
) //
| // or we found something else and can just skip it
Pat Break( ">" ) // match up to the closing > and throw it away
) //
) //
);
Data table of links and associated text鏈接和相關文本的數據表