简体   繁体   English

正则表达式拆分并合并为单个记录

[英]Regex split and merge into single record

In my C# application I'm using the below Regex to split the string ([A-Z0-9]{20}\d{0}).在我的 C# 应用程序中,我使用下面的正则表达式来拆分字符串 ([A-Z0-9]{20}\d{0})。 But it is splitting the ErrorCode and ErrorMsg as two different records but I need ErrorCode and ErrorMgs in the Single Array record.但它将 ErrorCode 和 ErrorMsg 拆分为两个不同的记录,但我需要 Single Array 记录中的 ErrorCode 和 ErrorMgs。 For Example: Current Logic:例如:当前逻辑:

[0] 05300030000GN0030018 [0] 05300030000GN0030018

[1 Field is required. [1 字段为必填项。

But I need like below one [0] 05300030000GN0030018Field is required.但我需要像下面一个 [0] 05300030000GN0030018Field 是必需的。

Current Implementation:当前实施:

我的正则表达式逻辑是这样返回的

Expected output预期 output

但我需要这种格式使用正则表达式

Assuming the msg is never empty and \d{0} was used to fail any match if the next char after [A-Z0-9]{20} is a digit, you can use假设msg永远不会为空,并且如果[A-Z0-9]{20}之后的下一个字符是数字,则使用\d{0}使任何匹配失败,您可以使用

var result = Regex.Matches(input, @"\b[A-Z0-9]{20}\D.*?(?=\b[A-Z0-9]{20}\D|\z)", RegexOptions.Singleline)
            .Cast<Match>()
            .Select(x => x.Value)
            .ToList();

See the regex demo .请参阅正则表达式演示 Note that in case msg can be empty you need to use a (?!\d) lookahead instead of \D , @"\b[A-Z0-9]{20}(?.\d)?*?(?=\b[A-Z0-9]{20}(?!\d)|\z)" .请注意,如果msg可以为空,您需要使用(?!\d)前瞻而不是\D@"\b[A-Z0-9]{20}(?.\d)?*?(?=\b[A-Z0-9]{20}(?!\d)|\z)"

Details :详情

  • \b - word boundary (need to make sure the char limit is fine) \b - 字边界(需要确保字符限制是好的)
  • [A-Z0-9]{20} - twenty uppercase ASCII letters or digits [A-Z0-9]{20} - 二十个大写 ASCII 字母或数字
  • \D - a non-digit char \D - 非数字字符
  • .*? - any zero or more chars as few as possible - 尽可能少的任何零个或多个字符
  • (?=\b[A-Z0-9]{20}\D|\z) - a positive lookahead that requires a word boundary, twenty uppercase ASCII letters or digits and a non-digit or end of string immediately to the right of the current location. (?=\b[A-Z0-9]{20}\D|\z) - 正向前瞻,需要单词边界、20 个大写 ASCII 字母或数字以及紧靠右侧的非数字或字符串结尾的当前位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM