Domanda

I need to convert text in either of the following two formats:

[[anyText~number]] OR [[anyText]]

to respective html format:

<span name="anyText~number">anyText</span> OR <span name="anyText">anyText</span>

example:

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

and

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

For this, I have created the following function in a NSString Category:

- (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];
}

Somewhere in my code, I am using the following:

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

The result of this is <span name=\"anyText~number\">anyText~number</span> . Is there a way I can operate upon the $1 (say removeTilderAndFurther($1) , in which case, my code becomes replaceWithString = @"<span name=\"$1\">removeTilderAndFurther($1)</span>";), so that I can achieve what I am after.

È stato utile?

Soluzione

What a great idea, adding a category to do this! I was able to do it like so:

NSString *regexString = @"\\[\\[((\\w+)(~\\d+)?)\\]\\]";
NSString *replaceWithString = @"<span name=\"$1\">$2</span>";
  1. First scenario without any numbers [[Hello]]:

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

    Its output is:

    rawStoryString: [[Hello]]
    rawStoryString: <span name="Hello">Hello</span>
    
  2. Second scenario with a tilde and number [[Thanks~1]]:

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

    Its output is:

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

Altri suggerimenti

Try this regex:

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

and replace with:

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

explanation:

\w Matches any word character.

\d Matches any decimal digit.

+ Matches the previous element one or more times.

(subexpression) Captures the matched subexpression and assigns it a zero-based ordinal number.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top