【问题标题】:Regex for html string in Objective CObjective C中html字符串的正则表达式
【发布时间】:2015-10-15 06:43:30
【问题描述】:

我得到一个带有标签的HTML 格式化字符串。但是“<br>”标签有一个反复无常。我得到随机格式的“<br>”标签,这会导致文本中有一些额外的空间。那么有什么解决方案可以用单个标签修剪这些多个“<br>”标签吗?

文本示例:-

"some text..... <br>"
"some text..... <br> <br>"   // <-- this cause some extra space.
"some text..... <br>\n"    // <-- this cause some extra space.
"some text..... <br>\n<br>" // <-- this cause some extra space.
"some text..... <br><br>\n     <br>" // <-- this cause some extra space.

简而言之,可以有多个“&lt;br&gt;”标签,其中包含空格和\n 字符。

我需要用单个“&lt;br&gt;”标签替换它。任何人都可以帮助我使用正则表达式吗?

注意:-我不想替换两个 "&lt;br&gt;" 标签之间的任何其他字符串,除了空格和 "\n" 。

写到现在的代码 -

NSMutableString *temp = [[NSMutableString alloc] initWithString:html];

            [temp replaceOccurrencesOfString:@"<br><br>" withString:@"<br>" options:0 range:NSMakeRange(0, [temp length])];
            [temp replaceOccurrencesOfString:@"<br>\n<br>" withString:@"<br>" options:0 range:NSMakeRange(0, [temp length])];
            [temp replaceOccurrencesOfString:@"<br>\n" withString:@"<br>" options:0 range:NSMakeRange(0, [temp length])];

这是一个静态字符串,需要regex

【问题讨论】:

  • 一个选项可以获取两个&lt;br&gt;标签之间的字符串并用\nspace修剪字符串。如果修剪后的字符串为空,则可以完全替换它。

标签: html ios objective-c regex nsstring


【解决方案1】:

101 Regex Demo

Find:    (<br>)(\s*\1)+
Replace: $1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多