Skip to content

Commit

Permalink
fix matchToClosingParenthesis for extracting more complex nsig functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Theta-Dev committed Aug 12, 2022
1 parent d120036 commit b672d37
Show file tree
Hide file tree
Showing 2 changed files with 54 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,45 @@ 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
public void find_closing_with_quotes() {
String expected = "{return \",}\\\"/\"}";
String string = "function(d){return \",}\\\"/\"}";

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

assertEquals(expected, substring);
}
}

0 comments on commit b672d37

Please sign in to comment.