【问题标题】:NSString add tags around occurrences of stringNSString 在出现的字符串周围添加标签
【发布时间】:2013-10-15 11:22:55
【问题描述】:

我需要像这样替换一个字符串;

NSString *temp = @"this is a sentence";

NSString *temp = @"this is a <span style=\"color:red\">sentence</span>"

现在我可以用下面这行来做到这一点;

temp = [temp stringByReplacingOccurrencesOfString:@"sentence" withString:@"<span style=\"color:red\">sentence</span>" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [temp length])];

现在使用上面的问题是我不知道替换或替换字符串的情况。我可以通过使用不敏感搜索来解决这个问题,但我需要替换的字符串是相同的格式为最终输出中的原始格式。

编辑

我过度简化了我的问题,因此更容易理解,但基本上我需要 stringByReplacingOccurrencesOfString 忽略大写/小写但同时在最终字符串上保持相同的大写/小写。

【问题讨论】:

  • 可能需要更多信息,但似乎您有足够专业的案例来编写自己的字符串替换。事情没有那么复杂。
  • 有任何例子吗?我想我必须做一些自定义字符串替换。
  • 尝试使用正则表达式。在搜索和替换复杂事物时,它有很大帮助。 (正则表达式——NSRegularExpressionSearch)

标签: ios replace nsstring


【解决方案1】:

您可以进行“正则表达式”替换,其中$0 在替换字符串中 指的是实际找到的子串:

NSString *temp = @"this is a foo, or a FOO";
NSString *result = [temp stringByReplacingOccurrencesOfString:@"foo"
                    withString:@"<span>$0</span>"
                       options:NSRegularExpressionSearch|NSCaseInsensitiveSearch
                         range:NSMakeRange(0, [temp length])];

结果:

这是一个foo,或者一个FOO

但请注意,搜索模式中的任何正则表达式“特殊字符”都必须进行转义。

【讨论】:

    【解决方案2】:

    您应该使用正则表达式来查找“句子”并在其周围添加标签。

    $1 指的是匹配的正则表达式组(sentence)

    \b 表示正则表达式中的单词边界。如果不包含它,也会匹配“asentenceb”之类的词。

    NSString *test = @"my test sentence is a Sentence. Oh yes, a sEnTenCe!";
    NSRange testRange = NSMakeRange(0, test.length);
    
    // Create regex object
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b(sentence)\\b" options:NSRegularExpressionCaseInsensitive error:&error];
    
    // Replace matches with template
    NSString *modifiedString = [regex stringByReplacingMatchesInString:test options:0 range:testRange withTemplate:@"<span style=\"color:red\">$1</span>"];
    

    注意:您可能可以使用 stringByReplacingOccurrencesOfString 进行类似的操作。

    【讨论】:

      【解决方案3】:

      检查是否 &lt;span style=\"color:red\"&gt;sentence&lt;/span&gt; 在你的 nsstring 中。如果没有,用新的 nsstring 替换原来的 nsstring

      【讨论】:

      • 我认为你误会了。我过度简化了我的问题,因此更容易理解,但本质上我需要 stringByReplacingOccurrencesOfString 同时忽略大写/小写,但同时在最终字符串上保持相同的大写/小写。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 2010-12-20
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多