【问题标题】:regex split implementation for sql serversql server 的正则表达式拆分实现
【发布时间】:2011-03-25 02:59:48
【问题描述】:

我创建了一个函数来在 sql 中实现 regex.split。代码如下:

private static IEnumerable<IndexedValue<T>> ToIndexedValue<T>(IEnumerable<T> list)
{
  int idx = 1;
  foreach (T value in list)
    yield return new IndexedValue<T>(++idx, value);
}
private struct IndexedValue<T>
{
  public int Index;
  public T Value;
  public IndexedValue(int index, T value)
  {
    Index = index;
    Value = value;
  }
}
[SqlFunction(FillRowMethodName = "FillSplit",
  TableDefinition = "[ID] int, [Value] nvarchar(max)")]
public static IEnumerable RegexSplit(SqlString input, SqlString pattern)
{
  if (input.IsNull)
    input = String.Empty;
  if (pattern.IsNull)
    pattern = String.Empty;
  try
  {
    return ToIndexedValue<string>(Regex.Split(input.Value, pattern.Value, Options));
  }
  catch
  {
    throw;
  }
}
public static void FillSplit(object obj, out int id, out SqlString value)
{
  IndexedValue<string> iv = (IndexedValue<string>)obj;
  id = iv.Index;
  value = iv.Value;
}

但是,当我尝试它时,我得到了 id 值但为空的文本值。有人可以帮忙吗?

【问题讨论】:

  • 这是一个骗子,寻找原创。编辑:不是真正的骗子,但我确实骗了我的答案:)

标签: .net regex sqlclr


【解决方案1】:

给你(编译为 SQL CLR 程序集):

using System.Collections;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
  [SqlFunction]
  public static bool RegexMatch(string expr, string regex)
  {
    return Regex.IsMatch(expr, regex);
  }

  [SqlFunction]
  public static string RegexReplace(string expr, string regex, string replace)
  {
    return Regex.Replace(expr, regex, replace);
  }

  [SqlFunction(FillRowMethodName="GetToken", 
       TableDefinition="Value nvarchar(max)")]
  public static IEnumerable RegexSplit(string expr, string regex)
  {
    return Regex.Split(expr, regex);
  }

  public static void GetToken(object row, out string str)
  {
     str = (string) row;
  }
}

原文来自:microsoft sql equivalent of mysql REGEXP

【讨论】:

    【解决方案2】:

    我怀疑您使用的正则表达式正在返回一个空字符串或空格数组。您是否尝试过为表达式本身设置一个简单的命令行测试框架?

    除了Options 未定义外,我看不出这段代码有什么问题。这是在别处定义的常量吗?

    【讨论】:

      猜你喜欢
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 2013-08-11
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多