Skip to content

Commit

Permalink
Handle curly braces inside strings in StringUtils.matchToClosingParen…
Browse files Browse the repository at this point in the history
…thesis

This is required to extract fully more complex YouTube nsig functions.
  • Loading branch information
Theta-Dev authored and AudricV committed Aug 12, 2022
1 parent d120036 commit 52ded6e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,13 @@ public static String matchToClosingParenthesis(@Nonnull final String string,
}

startIndex += start.length();
int endIndex = startIndex;
while (string.charAt(endIndex) != '{') {
++endIndex;
}
int endIndex = findNextParenthesis(string, startIndex, true);
++endIndex;

int openParenthesis = 1;
while (openParenthesis > 0) {
endIndex = findNextParenthesis(string, endIndex, false);

switch (string.charAt(endIndex)) {
case '{':
++openParenthesis;
Expand All @@ -46,4 +45,47 @@ public static String matchToClosingParenthesis(@Nonnull final String string,

return string.substring(startIndex, endIndex);
}

private static int findNextParenthesis(@Nonnull final String string,
final int offset,
final boolean onlyOpen) {
boolean lastEscaped = false;
char quote = ' ';

for (int i = offset; i < string.length(); i++) {
boolean thisEscaped = false;
final char c = string.charAt(i);

switch (c) {
case '{':
if (quote == ' ') {
return i;
}
break;
case '}':
if (!onlyOpen && quote == ' ') {
return i;
}
break;
case '\\':
if (!lastEscaped) {
thisEscaped = true;
}
break;
case '\'':
case '"':
if (!lastEscaped) {
if (quote == ' ') {
quote = c;
} else if (quote == c) {
quote = ' ';
}
}
}

lastEscaped = thisEscaped;
}

return -1;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,14 @@ public void lessClosing__success() {

assertEquals(expected, substring);
}

@Test
void find_closing_with_quotes() {
final String expected = "{return \",}\\\"/\"}";
final String string = "function(d){return \",}\\\"/\"}";

final String substring = matchToClosingParenthesis(string, "function(d)");

assertEquals(expected, substring);
}
}

0 comments on commit 52ded6e

Please sign in to comment.