Skip to content

Commit

Permalink
Fix adapting Regex for C# (#172)
Browse files Browse the repository at this point in the history
* add failing adaptable regex test
* fix adapting regex
  • Loading branch information
KurtGokhan authored Jul 11, 2021
1 parent d9dabfa commit 029c0f8
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
27 changes: 18 additions & 9 deletions src/Esprima/Scanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1574,22 +1574,31 @@ public Token ScanTemplate()
try
{
// Do we need to convert the expression to its .NET equivalent?
if (_adaptRegexp && options.HasFlag(RegexOptions.Multiline))
if (_adaptRegexp)
{
// Replace all non-escaped $ occurences by \r?$
// c.f. http://programmaticallyspeaking.com/regular-expression-multiline-mode-whats-a-newline.html

int index = 0;
var newPattern = pattern;
while ((index = newPattern.IndexOf("$", index, StringComparison.Ordinal)) != -1)

if (options.HasFlag(RegexOptions.Multiline))
{
if (index > 0 && newPattern[index - 1] != '\\')
// Replace all non-escaped $ occurences by \r?$
// c.f. http://programmaticallyspeaking.com/regular-expression-multiline-mode-whats-a-newline.html

int index = 0;
while ((index = newPattern.IndexOf("$", index, StringComparison.Ordinal)) != -1)
{
newPattern = newPattern.Substring(0, index) + @"\r?" + newPattern.Substring(index);
index += 4;
if (index > 0 && newPattern[index - 1] != '\\')
{
newPattern = newPattern.Substring(0, index) + @"\r?" + newPattern.Substring(index);
index += 4;
}
}
}

if (newPattern.Contains("[^]"))
{
newPattern = newPattern.Replace("[^]", "[^.]");
}

pattern = newPattern;
}

Expand Down
16 changes: 14 additions & 2 deletions test/Esprima.Tests/RegExpTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ private static Regex CreateRegex(string code)
};
var token = new Scanner(code, options).ScanRegExp();
return (Regex) token.Value;
}

}

[Theory]
[InlineData(@"/[^]*? (:[rp] [el] a[\w -]+)[^]*/")]
[InlineData(@"/[^]/")]
Expand All @@ -32,6 +32,18 @@ public void ShouldParseRegularExpression(string regexp)
var program = parser.ParseScript();

Assert.NotNull(program);
}

[Theory]
[InlineData(@"/[^]*? (:[rp] [el] a[\w -]+)[^]*/")]
[InlineData(@"/[^]/")]
[InlineData(@"/[^ ]/")]
public void ShouldGetNonNullRegexFromScanner(string regexp)
{
var scanner = new Scanner("", new ParserOptions { AdaptRegexp = true });
var regex = scanner.TestRegExp(regexp, "");

Assert.NotNull(regex);
}
}
}

0 comments on commit 029c0f8

Please sign in to comment.