1

我需要将文本转换为以下两种格式之一:

[[anyText~number]]或者[[anyText]]

到各自的html格式:

<span name="anyText~number">anyText</span>或者<span name="anyText">anyText</span>

例子:

[[Thanks~1]]<span name="Thanks~1">Thanks</span>

[[Hello]]<span name="Hello">Hello</span>

为此,我在 NSString 类别中创建了以下函数:

- (NSString*) stringByReplacingOccurrencesOfRegex:(NSString*)regexString withString:(NSString*)replaceWithString {
    NSError* error;
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
    NSRange fullrange = NSMakeRange(0,self.length);
    return [regex stringByReplacingMatchesInString:self options:NSMatchingWithTransparentBounds range:fullrange withTemplate:replaceWithString];
}

在我的代码的某处,我正在使用以下内容:

    regexString = @"\\[\\[([^\\]]*)\\]\\]";
    replaceWithString = @"<span name=\"$1\">$1</span>";
    rawStoryString = [rawStoryString stringByReplacingOccurrencesOfRegex:regexString withString:replaceWithString];

这样做的结果是<span name=\"anyText~number\">anyText~number</span>。有没有办法可以对$1(比如说removeTilderAndFurther($1),在这种情况下,我的代码变成replaceWithString = @"<span name=\"$1\">removeTilderAndFurther($1)</span>";)进行操作,这样我就可以实现我所追求的。

4

2 回答 2

0

试试这个正则表达式:

\[\[(\w+)(~\d+)?\]\]

并替换为:

<span name="$1$2">$1</span>

解释:

\w 匹配任何单词字符。

\d 匹配任何十进制数字。

+匹配前一个元素一次或多次。

(subexpression) 捕获匹配的子表达式并为其分配一个从零开始的序数。

于 2013-04-10T04:22:31.717 回答
0

多么棒的主意,添加一个类别来做到这一点!我能够这样做:

NSString *regexString = @"\\[\\[((\\w+)(~\\d+)?)\\]\\]";
NSString *replaceWithString = @"<span name=\"$1\">$2</span>";
  1. 没有任何数字的第一个场景[[Hello]]

    NSString *rawStoryString = @"[[Hello]]";
    NSLog(@"rawStoryString: %@", rawStoryString);
    rawStoryString = [rawStoryString stringByReplacingOccurrencesOfRegex:regexString withString:replaceWithString];
    NSLog(@"rawStoryString: %@", rawStoryString);
    

    它的输出是:

    rawStoryString: [[Hello]]
    rawStoryString: <span name="Hello">Hello</span>
    
  2. 带有波浪号和数字的第二种情况[[Thanks~1]]

    rawStoryString = @"[[Thanks~1]]";
    NSLog(@"rawStoryString: %@", rawStoryString);
    rawStoryString = [rawStoryString stringByReplacingOccurrencesOfRegex:regexString withString:replaceWithString];
    NSLog(@"rawStoryString: %@", rawStoryString);
    

    它的输出是:

    rawStoryString: [[Thanks~1]]
    rawStoryString: <span name="Thanks~1">Thanks</span>
    
于 2013-04-10T05:31:24.300 回答