[英]Need RegEx to return first paragraph or first n words
我正在尋找RegEx來返回段落中的第一個[n]單詞,或者如果段落包含少於[n]個單詞,則返回完整的段落。
例如,假設我最多需要前7個單詞:
<p>one two <tag>three</tag> four five, six seven eight nine ten.</p><p>ignore</p>
我得到:
one two <tag>three</tag> four five, six seven
對包含少於請求的字數的段落使用相同的RegEx:
<p>one two <tag>three</tag> four five.</p><p>ignore</p>
簡單地回復:
one two <tag>three</tag> four five.
我對此問題的嘗試產生了以下RegEx:
^(?:\<p.*?\>)((?:\w+\b.*?){1,7}).*(?:\</p\>)
但是,這只返回第一個單詞 - “one”。 它不起作用。 我覺得 。*? (在\\ w + \\ b之后)導致問題。
我哪里錯了? 任何人都可以提出一個有效的RegEx嗎?
僅供參考,我正在使用.Net 3.5的RegEX引擎(通過C#)
非常感謝
好的,完成重新編輯以確認新的“規范”:)
我很確定你不能用一個正則表達式做到這一點。 最好的工具肯定是HTML解析器。 我能用正則表達式得到的最接近的是兩步法。
首先,用以下內容隔離每個段落的內容:
<p>(.*?)</p>
如果段落可以跨越多行,則需要設置RegexOptions.Singleline
。
然后,在下一步中,迭代您的匹配並在每個匹配的Group[1].Value
上應用以下正則表達式Group[1].Value
:
((?:(\S+\s+){1,6})\w+)
這將匹配由空格/制表符/換行符分隔的前七個項目,忽略任何尾隨標點符號或非單詞字符。
但它會將由空格分隔的標簽視為其中一個項目,即在
One, two three <br\> four five six seven
它只會匹配到six
。 我想那是正則表達式,沒有辦法解決這個問題。
我有同樣的問題,並將一些Stack Overflow答案合並到這個課程中。 它使用HtmlAgilityPack,這是一個更好的工具。 呼叫:
Words(string html, int n)
得到n個單詞
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UmbracoUtilities
{
public class Text
{
/// <summary>
/// Return the first n words in the html
/// </summary>
/// <param name="html"></param>
/// <param name="n"></param>
/// <returns></returns>
public static string Words(string html, int n)
{
string words = html, n_words;
words = StripHtml(html);
n_words = GetNWords(words, n);
return n_words;
}
/// <summary>
/// Returns the first n words in text
/// Assumes text is not a html string
/// http://stackoverflow.com/questions/13368345/get-first-250-words-of-a-string
/// </summary>
/// <param name="text"></param>
/// <param name="n"></param>
/// <returns></returns>
public static string GetNWords(string text, int n)
{
StringBuilder builder = new StringBuilder();
//remove multiple spaces
//http://stackoverflow.com/questions/1279859/how-to-replace-multiple-white-spaces-with-one-white-space
string cleanedString = System.Text.RegularExpressions.Regex.Replace(text, @"\s+", " ");
IEnumerable<string> words = cleanedString.Split().Take(n + 1);
foreach (string word in words)
builder.Append(" " + word);
return builder.ToString();
}
/// <summary>
/// Returns a string of html with tags removed
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string StripHtml(string html)
{
HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);
var root = document.DocumentNode;
var stringBuilder = new StringBuilder();
foreach (var node in root.DescendantsAndSelf())
{
if (!node.HasChildNodes)
{
string text = node.InnerText;
if (!string.IsNullOrEmpty(text))
stringBuilder.Append(" " + text.Trim());
}
}
return stringBuilder.ToString();
}
}
}
聖誕節快樂!
編輯:我刪除了第2步和第3步的正則表達式提議,因為它是錯誤的(感謝評論者)。 此外,HTML結構需要展平。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.