If this regex pattern throws an exception?

If this regex pattern throws an exception? For me.

^\d{3}[a-z]

Error: parsing "^\d{3}[a" - Unterminated [] set.

I feel stupid. I do not get an error. (My RegexBuddy looks good with him.)

A bit more context, which I hope does not cause problems:

I am writing this for a user-defined CLR function in SQL Server:

[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic=true)]
  public static SqlChars Match(
    SqlChars input,
    SqlString pattern,
    SqlInt32 matchNb,
    SqlString name,
    SqlBoolean compile,
    SqlBoolean ignoreCase,
    SqlBoolean multiline,
    SqlBoolean singleline
    )
  {
    if (input.IsNull || pattern.IsNull || matchNb.IsNull || name.IsNull)
      return SqlChars.Null; 

    RegexOptions options = RegexOptions.IgnorePatternWhitespace |
      (compile.Value ? RegexOptions.Compiled : 0) |
      (ignoreCase.Value ? RegexOptions.IgnoreCase : 0) |
      (multiline.Value ? RegexOptions.Multiline : 0) |
      (singleline.Value ? RegexOptions.Singleline : 0);

    Regex regex = new Regex(pattern.Value, options);
    MatchCollection matches = regex.Matches(new string(input.Value));

    if (matches.Count == 0 || matchNb.Value > (matches.Count-1))
      return SqlChars.Null;

    Match match = matches[matchNb.Value];

    int number;
    if (Int32.TryParse(name.Value, out number))
    {
      return (number > (match.Groups.Count - 1)) ? 
        SqlChars.Null :
        new SqlChars(match.Groups[number].Value);
    }
    else
    {
      return new SqlChars(match.Groups[name.Value].Value);
    }
  }

Setting using

CREATE FUNCTION Match(@input NVARCHAR(max), @pattern NVARCHAR(8), @matchNb INT, @name NVARCHAR(64), @compile BIT, @ignoreCase BIT, @multiline BIT, @singleline BIT)
RETURNS NVARCHAR(max)
AS EXTERNAL NAME [RegEx].[UserDefinedFunctions].[Match]
GO

And test it with

SELECT dbo.Match(
  N'123x45.6789' --@input
, N'^\d{3}[a-z]' --@pattern
,0 --@matchNb
,0 --@name
,0 --@compile
,1 --@ignoreCase
,0 --@multiline
,1 --@singleline
)
+5
source share
1 answer

In the CREATE FUNCTION statement, you execute @pattern processing as NVARCHAR (8). This truncates your pattern to 8 characters.

+8
source

All Articles