Recursive pattern in NSRegularExpression











up vote
1
down vote

favorite
1












Similar question to Recursive pattern in regex, but in Objective-C.



I want to find the ranges or substrings of outer brackets.



Example input:



NSString *input = @"{a {b c}} {d e}";


Example result:



// yeah, I know, we can't put NSRange in an array, it is just to illustrate
NSArray *matchesA = @[NSMakeRange(0, 9), NSMakeRange(10, 5)]; // OK
NSArray *matchesB = @[NSMakeRange(1, 7), NSMakeRange(11, 3)]; // OK too

NSArray *outputA = @[@"{a {b c}}", @"{d e}"]; // OK
NSArray *outputB = @[@"a {b c}", @"d e"]; // OK too


Unfortunately, NSRegularExpression does not accept ?R apparently. Any alternative to match the outer brackets?










share|improve this question




















  • 6




    ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant (?R), not R.
    – Wiktor Stribiżew
    Oct 13 '15 at 7:27

















up vote
1
down vote

favorite
1












Similar question to Recursive pattern in regex, but in Objective-C.



I want to find the ranges or substrings of outer brackets.



Example input:



NSString *input = @"{a {b c}} {d e}";


Example result:



// yeah, I know, we can't put NSRange in an array, it is just to illustrate
NSArray *matchesA = @[NSMakeRange(0, 9), NSMakeRange(10, 5)]; // OK
NSArray *matchesB = @[NSMakeRange(1, 7), NSMakeRange(11, 3)]; // OK too

NSArray *outputA = @[@"{a {b c}}", @"{d e}"]; // OK
NSArray *outputB = @[@"a {b c}", @"d e"]; // OK too


Unfortunately, NSRegularExpression does not accept ?R apparently. Any alternative to match the outer brackets?










share|improve this question




















  • 6




    ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant (?R), not R.
    – Wiktor Stribiżew
    Oct 13 '15 at 7:27















up vote
1
down vote

favorite
1









up vote
1
down vote

favorite
1






1





Similar question to Recursive pattern in regex, but in Objective-C.



I want to find the ranges or substrings of outer brackets.



Example input:



NSString *input = @"{a {b c}} {d e}";


Example result:



// yeah, I know, we can't put NSRange in an array, it is just to illustrate
NSArray *matchesA = @[NSMakeRange(0, 9), NSMakeRange(10, 5)]; // OK
NSArray *matchesB = @[NSMakeRange(1, 7), NSMakeRange(11, 3)]; // OK too

NSArray *outputA = @[@"{a {b c}}", @"{d e}"]; // OK
NSArray *outputB = @[@"a {b c}", @"d e"]; // OK too


Unfortunately, NSRegularExpression does not accept ?R apparently. Any alternative to match the outer brackets?










share|improve this question















Similar question to Recursive pattern in regex, but in Objective-C.



I want to find the ranges or substrings of outer brackets.



Example input:



NSString *input = @"{a {b c}} {d e}";


Example result:



// yeah, I know, we can't put NSRange in an array, it is just to illustrate
NSArray *matchesA = @[NSMakeRange(0, 9), NSMakeRange(10, 5)]; // OK
NSArray *matchesB = @[NSMakeRange(1, 7), NSMakeRange(11, 3)]; // OK too

NSArray *outputA = @[@"{a {b c}}", @"{d e}"]; // OK
NSArray *outputB = @[@"a {b c}", @"d e"]; // OK too


Unfortunately, NSRegularExpression does not accept ?R apparently. Any alternative to match the outer brackets?







objective-c regex nsregularexpression recursive-regex






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 9:56

























asked Oct 13 '15 at 7:17









Cœur

17.3k9102142




17.3k9102142








  • 6




    ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant (?R), not R.
    – Wiktor Stribiżew
    Oct 13 '15 at 7:27
















  • 6




    ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant (?R), not R.
    – Wiktor Stribiżew
    Oct 13 '15 at 7:27










6




6




ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant (?R), not R.
– Wiktor Stribiżew
Oct 13 '15 at 7:27






ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant (?R), not R.
– Wiktor Stribiżew
Oct 13 '15 at 7:27














1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










Going for manual solution.



Assuming:



NSString *text = @"{a {b c}} {d e}";


nice solution without regex



NSUInteger len = text.length;
unichar buffer[len + 1];
[text getCharacters:buffer range:NSMakeRange(0, len)];
NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
NSInteger depth = 0;
NSUInteger location = NSNotFound;
for (NSUInteger i = 0; i < len; i++) {
if (buffer[i] == '{')
{
if (depth == 0)
location = i;
depth++;
}
else if (buffer[i] == '}')
{
depth--;
if (depth == 0)
[results addObject:[NSValue valueWithRange:NSMakeRange(location, i - location + 1)]];
}
}

return results;


ugly solution with regex



NSString *innerPattern = @"\{[^{}]*\}";
NSRegularExpression *innerBracketsRegExp = [NSRegularExpression regularExpressionWithPattern:innerPattern options:0 error:nil];
// getting deepest matches
NSArray<NSTextCheckingResult *> *deepestMatches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];
// stripping them from text
text = [text stringByReplacingOccurrencesOfString:innerPattern withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, text.length)];
// getting new deepest matches
NSArray<NSTextCheckingResult *> *depth2Matches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];

// merging the matches of different depth
NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
for (NSTextCheckingResult *cr in depth2Matches) {
[results addObject:[NSValue valueWithRange:cr.range]];
}
for (NSTextCheckingResult *cr in deepestMatches) {
__block BOOL merged = NO;
[results enumerateObjectsUsingBlock:^(NSValue * _Nonnull value, NSUInteger idx, BOOL * _Nonnull stop) {
if (merged)
[results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location + cr.range.length, value.rangeValue.length)]];
else if (NSLocationInRange(cr.range.location, value.rangeValue))
{
[results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location, value.rangeValue.length + cr.range.length)]];
merged = YES;
}
else if (cr.range.location < value.rangeValue.location)
{
[results insertObject:[NSValue valueWithRange:cr.range] atIndex:idx];
merged = YES;
}
}];
if (!merged)
[results addObject:[NSValue valueWithRange:cr.range]];
}

return results;





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33096411%2frecursive-pattern-in-nsregularexpression%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    Going for manual solution.



    Assuming:



    NSString *text = @"{a {b c}} {d e}";


    nice solution without regex



    NSUInteger len = text.length;
    unichar buffer[len + 1];
    [text getCharacters:buffer range:NSMakeRange(0, len)];
    NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
    NSInteger depth = 0;
    NSUInteger location = NSNotFound;
    for (NSUInteger i = 0; i < len; i++) {
    if (buffer[i] == '{')
    {
    if (depth == 0)
    location = i;
    depth++;
    }
    else if (buffer[i] == '}')
    {
    depth--;
    if (depth == 0)
    [results addObject:[NSValue valueWithRange:NSMakeRange(location, i - location + 1)]];
    }
    }

    return results;


    ugly solution with regex



    NSString *innerPattern = @"\{[^{}]*\}";
    NSRegularExpression *innerBracketsRegExp = [NSRegularExpression regularExpressionWithPattern:innerPattern options:0 error:nil];
    // getting deepest matches
    NSArray<NSTextCheckingResult *> *deepestMatches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];
    // stripping them from text
    text = [text stringByReplacingOccurrencesOfString:innerPattern withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, text.length)];
    // getting new deepest matches
    NSArray<NSTextCheckingResult *> *depth2Matches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];

    // merging the matches of different depth
    NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
    for (NSTextCheckingResult *cr in depth2Matches) {
    [results addObject:[NSValue valueWithRange:cr.range]];
    }
    for (NSTextCheckingResult *cr in deepestMatches) {
    __block BOOL merged = NO;
    [results enumerateObjectsUsingBlock:^(NSValue * _Nonnull value, NSUInteger idx, BOOL * _Nonnull stop) {
    if (merged)
    [results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location + cr.range.length, value.rangeValue.length)]];
    else if (NSLocationInRange(cr.range.location, value.rangeValue))
    {
    [results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location, value.rangeValue.length + cr.range.length)]];
    merged = YES;
    }
    else if (cr.range.location < value.rangeValue.location)
    {
    [results insertObject:[NSValue valueWithRange:cr.range] atIndex:idx];
    merged = YES;
    }
    }];
    if (!merged)
    [results addObject:[NSValue valueWithRange:cr.range]];
    }

    return results;





    share|improve this answer

























      up vote
      0
      down vote



      accepted










      Going for manual solution.



      Assuming:



      NSString *text = @"{a {b c}} {d e}";


      nice solution without regex



      NSUInteger len = text.length;
      unichar buffer[len + 1];
      [text getCharacters:buffer range:NSMakeRange(0, len)];
      NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
      NSInteger depth = 0;
      NSUInteger location = NSNotFound;
      for (NSUInteger i = 0; i < len; i++) {
      if (buffer[i] == '{')
      {
      if (depth == 0)
      location = i;
      depth++;
      }
      else if (buffer[i] == '}')
      {
      depth--;
      if (depth == 0)
      [results addObject:[NSValue valueWithRange:NSMakeRange(location, i - location + 1)]];
      }
      }

      return results;


      ugly solution with regex



      NSString *innerPattern = @"\{[^{}]*\}";
      NSRegularExpression *innerBracketsRegExp = [NSRegularExpression regularExpressionWithPattern:innerPattern options:0 error:nil];
      // getting deepest matches
      NSArray<NSTextCheckingResult *> *deepestMatches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];
      // stripping them from text
      text = [text stringByReplacingOccurrencesOfString:innerPattern withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, text.length)];
      // getting new deepest matches
      NSArray<NSTextCheckingResult *> *depth2Matches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];

      // merging the matches of different depth
      NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
      for (NSTextCheckingResult *cr in depth2Matches) {
      [results addObject:[NSValue valueWithRange:cr.range]];
      }
      for (NSTextCheckingResult *cr in deepestMatches) {
      __block BOOL merged = NO;
      [results enumerateObjectsUsingBlock:^(NSValue * _Nonnull value, NSUInteger idx, BOOL * _Nonnull stop) {
      if (merged)
      [results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location + cr.range.length, value.rangeValue.length)]];
      else if (NSLocationInRange(cr.range.location, value.rangeValue))
      {
      [results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location, value.rangeValue.length + cr.range.length)]];
      merged = YES;
      }
      else if (cr.range.location < value.rangeValue.location)
      {
      [results insertObject:[NSValue valueWithRange:cr.range] atIndex:idx];
      merged = YES;
      }
      }];
      if (!merged)
      [results addObject:[NSValue valueWithRange:cr.range]];
      }

      return results;





      share|improve this answer























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        Going for manual solution.



        Assuming:



        NSString *text = @"{a {b c}} {d e}";


        nice solution without regex



        NSUInteger len = text.length;
        unichar buffer[len + 1];
        [text getCharacters:buffer range:NSMakeRange(0, len)];
        NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
        NSInteger depth = 0;
        NSUInteger location = NSNotFound;
        for (NSUInteger i = 0; i < len; i++) {
        if (buffer[i] == '{')
        {
        if (depth == 0)
        location = i;
        depth++;
        }
        else if (buffer[i] == '}')
        {
        depth--;
        if (depth == 0)
        [results addObject:[NSValue valueWithRange:NSMakeRange(location, i - location + 1)]];
        }
        }

        return results;


        ugly solution with regex



        NSString *innerPattern = @"\{[^{}]*\}";
        NSRegularExpression *innerBracketsRegExp = [NSRegularExpression regularExpressionWithPattern:innerPattern options:0 error:nil];
        // getting deepest matches
        NSArray<NSTextCheckingResult *> *deepestMatches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];
        // stripping them from text
        text = [text stringByReplacingOccurrencesOfString:innerPattern withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, text.length)];
        // getting new deepest matches
        NSArray<NSTextCheckingResult *> *depth2Matches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];

        // merging the matches of different depth
        NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
        for (NSTextCheckingResult *cr in depth2Matches) {
        [results addObject:[NSValue valueWithRange:cr.range]];
        }
        for (NSTextCheckingResult *cr in deepestMatches) {
        __block BOOL merged = NO;
        [results enumerateObjectsUsingBlock:^(NSValue * _Nonnull value, NSUInteger idx, BOOL * _Nonnull stop) {
        if (merged)
        [results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location + cr.range.length, value.rangeValue.length)]];
        else if (NSLocationInRange(cr.range.location, value.rangeValue))
        {
        [results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location, value.rangeValue.length + cr.range.length)]];
        merged = YES;
        }
        else if (cr.range.location < value.rangeValue.location)
        {
        [results insertObject:[NSValue valueWithRange:cr.range] atIndex:idx];
        merged = YES;
        }
        }];
        if (!merged)
        [results addObject:[NSValue valueWithRange:cr.range]];
        }

        return results;





        share|improve this answer












        Going for manual solution.



        Assuming:



        NSString *text = @"{a {b c}} {d e}";


        nice solution without regex



        NSUInteger len = text.length;
        unichar buffer[len + 1];
        [text getCharacters:buffer range:NSMakeRange(0, len)];
        NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
        NSInteger depth = 0;
        NSUInteger location = NSNotFound;
        for (NSUInteger i = 0; i < len; i++) {
        if (buffer[i] == '{')
        {
        if (depth == 0)
        location = i;
        depth++;
        }
        else if (buffer[i] == '}')
        {
        depth--;
        if (depth == 0)
        [results addObject:[NSValue valueWithRange:NSMakeRange(location, i - location + 1)]];
        }
        }

        return results;


        ugly solution with regex



        NSString *innerPattern = @"\{[^{}]*\}";
        NSRegularExpression *innerBracketsRegExp = [NSRegularExpression regularExpressionWithPattern:innerPattern options:0 error:nil];
        // getting deepest matches
        NSArray<NSTextCheckingResult *> *deepestMatches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];
        // stripping them from text
        text = [text stringByReplacingOccurrencesOfString:innerPattern withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, text.length)];
        // getting new deepest matches
        NSArray<NSTextCheckingResult *> *depth2Matches = [innerBracketsRegExp matchesInString:text options:0 range:NSMakeRange(0, text.length)];

        // merging the matches of different depth
        NSMutableOrderedSet<NSValue *> *results = [NSMutableOrderedSet orderedSet];
        for (NSTextCheckingResult *cr in depth2Matches) {
        [results addObject:[NSValue valueWithRange:cr.range]];
        }
        for (NSTextCheckingResult *cr in deepestMatches) {
        __block BOOL merged = NO;
        [results enumerateObjectsUsingBlock:^(NSValue * _Nonnull value, NSUInteger idx, BOOL * _Nonnull stop) {
        if (merged)
        [results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location + cr.range.length, value.rangeValue.length)]];
        else if (NSLocationInRange(cr.range.location, value.rangeValue))
        {
        [results replaceObjectAtIndex:idx withObject:[NSValue valueWithRange:NSMakeRange(value.rangeValue.location, value.rangeValue.length + cr.range.length)]];
        merged = YES;
        }
        else if (cr.range.location < value.rangeValue.location)
        {
        [results insertObject:[NSValue valueWithRange:cr.range] atIndex:idx];
        merged = YES;
        }
        }];
        if (!merged)
        [results addObject:[NSValue valueWithRange:cr.range]];
        }

        return results;






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 13 '15 at 10:17









        Cœur

        17.3k9102142




        17.3k9102142






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33096411%2frecursive-pattern-in-nsregularexpression%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine