我正在开发的HTML系统允许终端用户在某些情况下输入.NET格式的文本。在其中一些地方,我们希望保留所有标记,但去掉所有尾随的换行符(但在正文中保留所有换行符)。
做这件事最好的方法是什么?(我可以想出一些方法来做到这一点,但我确信它们不是最好的。)
发布于 2008-09-25 18:53:39
正如@Mitch所说,
// using System.Text.RegularExpressions;
/// <summary>
/// Regular expression built for C# on: Thu, Sep 25, 2008, 02:01:36 PM
/// Using Expresso Version: 2.1.2150, http://www.ultrapico.com
///
/// A description of the regular expression:
///
/// Match expression but don't capture it. [\<br\s*/?\>], any number of repetitions
/// \<br\s*/?\>
/// <
/// br
/// Whitespace, any number of repetitions
/// /, zero or one repetitions
/// >
/// End of line or string
///
///
/// </summary>
public static Regex regex = new Regex(
@"(?:\<br\s*/?\>)*$",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
regex.Replace(text, string.Empty);发布于 2008-09-25 19:10:57
对bdukes代码的小改动,这样应该会更快,因为它不会回溯。
public static Regex regex = new Regex(
@"(?:\<br[^>]*\>)*$",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
regex.Replace(text, string.Empty);发布于 2008-09-25 18:45:44
我肯定这也不是最好的方法,但它应该可以工作,除非你有尾随空格或其他什么。
while (myHtmlString.EndsWith("<br>"))
{
myHtmlString = myHtmlString.SubString(0, myHtmlString.Length - 4);
}https://stackoverflow.com/questions/135151
复制相似问题