【问题标题】:Conditionally replace section of string [duplicate]有条件地替换字符串的一部分[重复]
【发布时间】:2013-02-17 08:41:57
【问题描述】:

我有一个关于 C# 中字符串操作的问题。

假设我有一个字符串:

"Today I ate a <a href="link here "> chocolate </a> at the <a href=\"another link here"> supermarket</a>. It was a brand of <a href=\"3rd link">Contoso</a>

我愿意:

"Today I ate a  chocolate at the supermarket. It was a brand of Contoso.

我可以删除其中的 &lt;/a&gt; 部分,但不确定如何删除 &lt;a href&gt; 之间的所有内容和任何内容

我该怎么做呢?

提前致谢!

【问题讨论】:

标签: c# regex


【解决方案1】:

在这里找到了一个很好的答案:Need regular expression to remove <a href="xx">Name</a> tags from a string

也有效!

随时发布任何更好、更有效的方法。

【讨论】:

    【解决方案2】:

    Regex 可能是最好的选择,但是如果您不想使用Regex,那么按照您想要的方式解析字符串将会非常繁琐。

    一个想法可能是通过&lt;/a&gt; 拆分字符串,然后获取&lt;a&gt; 的所有字符

     var result = new string (input.Split(new string[] { "</a>" }, StringSplitOptions.RemoveEmptyEntries)
        .SelectMany(s => s.Where((c, i) => i < s.IndexOf("<a") || i > s.IndexOf(">"))).ToArray());
    

    所以我会坚持使用Regex,如果它对你有用,因为它比使用字符串选项容易得多

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 2016-09-22
      • 2017-04-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 2022-07-18
      相关资源
      最近更新 更多