带分隔符的正则表达式

时间:2014-04-22 10:56:47

标签: .net regex

我想在.NET中使用正则表达式解析一些字符串,其格式为分隔符为'值,分隔符为&值:

'A$04'&'A&&&'&'585262&YY'&'05555'

我发现的问题是分隔符&也可以出现在每个值中。

请问您如何在不使用循环的情况下执行此操作?我尝试了一些正则表达式,但没有成功。

4 个答案:

答案 0 :(得分:0)

尝试

'[^']+'(&'[^']+')*

除非你的字段内有撇号,否则这应该有效。请注意,我认为您的字段不能为空 - 将+替换为*以处理此情况。

答案 1 :(得分:0)

string[] splitArray = null;
try {
    splitArray = Regex.Split(subjectString, "'(.*?)'");
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}


Match the character “'” literally «'»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is not a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “'” literally «'»

答案 2 :(得分:0)

另一种分裂方式:

string[] values = Regex.Split("'A$04'&'A&&&'&'585262&YY'&'05555'", "(?<=')&(?=')");

我们按&分隔'后跟'

(?<=')&(?=')

Regular expression visualization

Debuggex Demo

答案 3 :(得分:0)

试试这个..

        var r = new Regex("'[A-Z0-9&$]*'",RegexOptions.IgnoreCase);
        var matches = r.Matches("'A$04'&'A&&&'&'585262&YY'&'05555'");
        foreach (var match in matches)
        {
            var finalValue = match.ToString().Replace("'","");
        }