使用正規表示式將Html轉換為純文字

2021-04-02 19:27:29 字數 2000 閱讀 1877

在網頁剛流行起來的時候,提取html中的文字有乙個簡單的方法,就是將html文字(包含標記)中的所有以「<」符號開頭到以「>」符號之間的內容去掉即可。

但對於現在複雜的網頁而言,用這種方法提取出來的文字會有大量的空格、空行、script段落、還有一些html轉義字元,效果很差。

下面用正規表示式來提取html中的文字,

**的實現的思路是:

a、先將html文字中的所有空格、換行符去掉(因為html中的空格和換行是被忽略的)

b、將)", string.empty, regexoptions.ignorecase);

result = regex.replace(result, @"<( )*script([^>])*>", ")", string.empty, regexoptions.ignorecase);

//remove all styles

result = regex.replace(result, @"<( )*style([^>])*>", ")", string.empty, regexoptions.ignorecase);

//insert tabs in spaces of tags

result = regex.replace(result, @"<( )*td([^>])*>", " ", regexoptions.ignorecase);

//insert line breaks in places of

and tags

result = regex.replace(result, @"<( )*br( )*>", "/r", regexoptions.ignorecase);

result = regex.replace(result, @"<( )*li( )*>", "/r", regexoptions.ignorecase);

//insert line paragraphs in places of and tags

result = regex.replace(result, @"<( )*tr([^>])*>", "/r/r", regexoptions.ignorecase);

result = regex.replace(result, @"<( )*p([^>])*>", "/r/r", regexoptions.ignorecase);

//remove anything thats enclosed inside < >

result = regex.replace(result, @"<[^>]*>", string.empty, regexoptions.ignorecase);

//replace special characters:

result = regex.replace(result, @"&", "&", regexoptions.ignorecase);

result = regex.replace(result, @" ", " ", regexoptions.ignorecase);

result = regex.replace(result, @"<", "<", regexoptions.ignorecase);

result = regex.replace(result, @">", ">", regexoptions.ignorecase);

result = regex.replace(result, @"&(.);", string.empty, regexoptions.ignorecase);

//remove extra line breaks and tabs

result = regex.replace(result, @" ( )+", " ");

result = regex.replace(result, "(/r)( )+(/r)", "/r/r");

result = regex.replace(result, @"(/r/r)+", "/r/n");

return result;

}

}//end class

}//end namespace

HTML 正規表示式

表示式概念 一種字串檢索模式 表現為字串形式的object物件 可進行文字搜尋和替換。在前端頁面中一般用於表單驗證 語法 正則字面量表達方式 正規表示式主體 修飾符 可選 var reg abc i 實際開發中正規表示式會配合字串的search和replace方法來使用 search 用於檢索與正規...

將表示式轉換為逆波蘭表示式

給定乙個表示式字串陣列,返回該表示式的逆波蘭表示式 即去掉括號 樣例對於 3 4 5 的表示式 該表示式可表示為 3 4 5 返回 3 4 5 該表示式可表示為 3 4 5 class solution else if expression i else if expression i operat...

將中綴表示式轉換為字首表示式

將中綴表示式轉換為字首表示式 遵循以下步驟 1 初始化兩個棧 運算子棧 s1和儲存中間結果的棧s2 2 從右至左掃瞄中綴表示式 3 遇到運算元時,將其壓入s2 4 遇到運算子時,比較其與 s1棧頂運算子的優先順序 4 1 如果 s1為空,或棧頂運算子為右括號 則直接將此運算子入棧 4 2 否則,若優...