-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
ExpressionFactory.cs
60 lines (53 loc) · 2.22 KB
/
ExpressionFactory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Text.RegularExpressions;
namespace CucumberExpressions;
/// <summary>
/// Creates a {@link CucumberExpression} or {@link RegularExpression} from a {@link String}
/// using heuristics.
/// </summary>
public class ExpressionFactory
{
private static readonly Regex BeginAnchorRe = new("^\\^.*");
private static readonly Regex EndAnchorRe = new(".*\\$$");
private static readonly Regex ScriptStyleRegexpRe = new("^/(?<inner>.*)/$");
private static readonly Regex ParameterPatternRe = new("((?:\\\\){0,2})\\{([^}]*)\\}");
private readonly IParameterTypeRegistry _parameterTypeRegistry;
public ExpressionFactory(IParameterTypeRegistry parameterTypeRegistry)
{
_parameterTypeRegistry = parameterTypeRegistry;
}
public IExpression CreateExpression(String expressionString)
{
if (BeginAnchorRe.IsMatch(expressionString) || EndAnchorRe.IsMatch(expressionString))
{
return createRegularExpressionWithAnchors(expressionString);
}
var scriptStyleRegexpMatch = ScriptStyleRegexpRe.Match(expressionString);
if (scriptStyleRegexpMatch.Success)
{
return new RegularExpression(new(scriptStyleRegexpMatch.Groups["inner"].Value));
}
if (IsRegularExpression(expressionString))
return createRegularExpressionWithAnchors(expressionString);
return new CucumberExpression(expressionString, _parameterTypeRegistry);
}
protected virtual bool IsRegularExpression(string expressionString)
{
return false; // additional heuristics can be implemented in derived classes
}
private RegularExpression createRegularExpressionWithAnchors(string expressionString)
{
try
{
return new RegularExpression(new(expressionString));
}
catch (ArgumentException e)
{
if (ParameterPatternRe.IsMatch(expressionString))
{
throw new CucumberExpressionException("You cannot use anchors (^ or $) in Cucumber Expressions. Please remove them from " + expressionString, e);
}
throw new CucumberExpressionException($"Invalid regular expression: '{expressionString}'", e);
}
}
}