【问题标题】:C# REGEX need to be correctedC# REGEX 需要更正
【发布时间】:2013-08-29 08:09:59
【问题描述】:

我正在制作一个 C# 正则表达式来查找和替换与 html 内容相关的模式。 我需要得到所有类似的东西:

<table border=0 align=center id=mytable5>

这样改正:

<table border="0" align="center" id="mytable5">

我试过了:

String pattern = @"\s(?<element>[a-z])=(?<valeur>\d+?[a-z])\s?[\>]";
String replacePattern = "${element}=[\"]${valeur}[\"]";
html = Regex.Replace(html, pattern, replacePattern, RegexOptions.IgnoreCase);

但绝对没有效果。 任何帮助将不胜感激。 谢谢大家


其实King King,你的正则表达式有问题

<table border=0 align="center" id="mytable5">

会给

<table border="0" align=""center"" id=""mytable5"">

这就是为什么正则表达式必须检查这个

[a 空格][a-z]=[a-z0-9][a 空格或'>']

【问题讨论】:

  • 这里不是让正则表达式理解 html,而只是字符串中的模式替换,仅此而已。但是感谢您的链接顺便说一句,我喜欢字母在底部泄漏的方式,视觉效果很好

标签: c# html regex replace


【解决方案1】:
var html = "<table border=0 align=center id=mytable5>";
html = Regex.Replace(html, @"=\s*(\S+?)([ >])", "=\"${1}\"${2}", RegexOptions.IgnoreCase);

【讨论】:

  • @JayCohen 没问题,如果对您有帮助,接受答案就足够了。
  • 你的正则表达式有问题,请查看我刚刚添加的第一篇文章有​​什么问题
【解决方案2】:

我明白了

String pattern = @"([a-z]+)=([a-z0-9_-]+)([ >])";
String replacePattern = "${1}=\"${2}\"${3}";
html = Regex.Replace(html, pattern, replacePattern, RegexOptions.IgnoreCase);

会得到

<table border=0 align="center" id="mytable5">

更正如下:

<table border="0" align="center" id="mytable5">

感谢King King为我指明了道路

【讨论】:

    猜你喜欢
    • 2014-10-31
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2012-07-27
    • 2021-08-19
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多