Question

I am using a NSScanner to detect text bound by [square brackets] in a string, and convert it into HTML hyperlinks. I hope to turn convert this text in the following way:

This [is an] example of the [text] I'm using

should convert to

This <a href = "is an">is an</a> example of the <a href = "text">text</a> I'm using

I've implemented a NSScanner, but in order to make it work properly, I need to extract both the first and second of the square brackets.

Here's the current state of my code:

NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:stringWithBrackets];

NSString *stringWithoutBrackets;
while ([theScanner isAtEnd] == NO) {
    [theScanner scanUpToString:@"[" intoString:NULL];
    [theScanner scanUpToString:@"]" intoString:&text];

<BREAK>

At this breakpoint, I have a string returned, which does not contain the closing bracket. So, for the example text string shown above, the contents of NSString *text at the first breakpoint is

[is an

In order to properly manipulate the string, I need to work with both the opening and closing bracket.

Essentially, my question is: how do I advance the NSScanner on one character, and include that character into the variable 'text'?

Was it helpful?

Solution

You can skip the ] character with scanString:

if ([theScanner scanString:@"]" intoString:NULL]) {
    text = [text stringByAppendingString:@"]"];
} else {
    // Next character is not ']'
}

The else case would only happen if there is no matching ] character. text contains the part from [ to the end of the string in that case.

Alternatively, you could use NSRegularExpression and e.g. the matchesInString method which returns an array of all ranges in the string matching the regular expression.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top