c# - 正则表达式按最后一个索引拆分

标签 c# .net sql-server regex sql-server-2016

我有基于 .net regex 函数的 SQL CLR 函数,以便通过正则表达式拆分值。在其中一种情况下,我使用函数将值拆分为 | .问题是我发现其中一个值有双 || .因为,我确定第二个值(正确的值)是一个数字,所以我知道第二个 |是第一个值(左值)的一部分。

我有:

慂||2215

那应该拆分成:

慂|
2215

我正在使用这个表达式进行拆分 [|] .我认为为了让它工作,我需要使用 Zero-width negative look ahead assertion.但是当我按 (?![|])[|] 拆分时我得到:

慂||2215

如果我尝试向后看 - (?<![|])[|]我得到:

慂
|2215

但我需要管道成为第一个值的一部分。

有人可以帮我解决这个问题吗?只寻找正则表达式解决方案,因为现在无法更改应用程序。


如果有人需要,这里是函数:

/// <summary>
///     Splits an input string into an array of substrings at the positions defined by a regular expression pattern.
///     Index of each value is returned.
/// </summary>
/// <param name="sqlInput">The source material</param>
/// <param name="sqlPattern">How to parse the source material</param>
/// <returns></returns>
[SqlFunction(FillRowMethodName = "FillRowForSplitWithOrder")]
public static IEnumerable SplitWithOrder(SqlString sqlInput, SqlString sqlPattern)
{
    string[] substrings;
    List<Tuple<SqlInt64, SqlString>> values = new List<Tuple<SqlInt64, SqlString>>(); ;

    if (sqlInput.IsNull || sqlPattern.IsNull)
    {
        substrings = new string[0];
    }
    else
    {
        substrings = Regex.Split(sqlInput.Value, sqlPattern.Value);
    }

    for (int index = 0; index < substrings.Length; index++)
    {
        values.Add(new Tuple<SqlInt64, SqlString>(new SqlInt64(index), new SqlString(substrings[index])));
    }

    return values;
}

最佳答案

你应该在这里使用负向前瞻而不是后视

[|](?![|])

参见 regex demo

详情

  • [|] - 匹配 | 字符
  • (?![|]) - 不需要 | 字符立即位于当前位置右侧的否定前瞻。

enter image description here

关于c# - 正则表达式按最后一个索引拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49796989/

相关文章:

sql - 我们可以在 SQL Server 中的两个存储过程之间进行连接吗

sql - "NOT IN"在SQL查询中的性能

c# - WPF 项目中每个字典条目必须有一个关联的键错误

c# - 任务 WhenAll 用法

c# - 使用包含的 xsd 文件编译模式

c# - 什么是好的(如果有的话).NET Windows 自动化库?

c# - 为什么 Add-Migration 有时会创建重复的迁移?

c# - 线程中止留下僵尸事务和损坏的 SqlConnection

c# - 是否可以使用 VS2008 在 C# 中自动连接事件?

c# - 如何在第三个项目中引用和使用 .NET Core 3.0 和 .NET EF 4.7 项目,并使用它们的数据库连接?