Recursive pattern in NSRegularExpression
up vote
1
down vote
favorite
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
add a comment |
up vote
1
down vote
favorite
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
6
ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant(?R)
, notR
.
– Wiktor Stribiżew
Oct 13 '15 at 7:27
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
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
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
objective-c regex nsregularexpression recursive-regex
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)
, notR
.
– Wiktor Stribiżew
Oct 13 '15 at 7:27
add a comment |
6
ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant(?R)
, notR
.
– 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
add a comment |
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;
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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;
add a comment |
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;
add a comment |
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;
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;
answered Oct 13 '15 at 10:17
Cœur
17.3k9102142
17.3k9102142
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
6
ICU regex flavor does not support recursion. You will need to parse the strings "manually". And FYI, you must have meant
(?R)
, notR
.– Wiktor Stribiżew
Oct 13 '15 at 7:27