c#regex匹配排除第一个和最后一个字符

问题描述 投票:1回答:2

我对正则表达式一无所知所以我要求这个伟大的社区帮助我。在SO的帮助下,我设法编写了这个正则表达式:

    string input = "((isoCode=s)||(isoCode=a))&&(title=s)&&((ti=2)&&(t=2))||(t=2&&e>5)";
    string pattern = @"\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!))\)|&&|\|\|";
    MatchCollection matches = Regex.Matches(input, pattern);
    foreach (Match match in matches)
    {
        Console.WriteLine(match.Groups[0].Value);
    }

结果是:

((isoCode=s)||(isoCode=a))
&&
(title=s)
&&
((ti=2)&&(t=2))
||
(t=2&&e>5)

但我需要这样的结果(没有第一个/最后一个“(”,“)”):

(isoCode=s)||(isoCode=a)
&&
title=s
&&
(ti=2)&&(t=2)
||
t=2&&e>5

可以吗?我知道我可以使用substring(删除第一个和最后一个字符),但我想知道它是否可以用正则表达式完成。

c# regex
2个回答
4
投票

你可以用

\((?<R>(?>\((?<DEPTH>)|\)(?<-DEPTH>)|[^()]+)*(?(DEPTH)(?!)))\)|(?<R>&&|\|\|)

查看regex demo,获取Group“R”值。

细节

  • \( - 一个开放的(
  • (?<R> - R命名小组的开始: (?> - 原子团的开始: \((?<DEPTH>)| - 一个开放的(和一个空字符串被推到DEPTH组堆栈或 \)(?<-DEPTH>)| - 关闭)和一个空字符串从DEPTH组栈中弹出或 [^()]+ - 除了()之外的1个字符 )* - 零次或多次重复 (?(DEPTH)(?!)) - 一个条件结构,用于检查close括号和开括号的数量是否平衡
  • ) - R命名组的结尾
  • \) - 关闭)
  • | - 或
  • (?<R>&&|\|\|) - 另一个出现的R组匹配2个子模式中的任何一个: && - 一个&&子串 | - 或 \|\| - 一个||子串。

enter image description here

C#代码:

var pattern = @"\((?<R>(?>\((?<DEPTH>)|\)(?<-DEPTH>)|[^()]+)*(?(DEPTH)(?!)))\)|(?<R>&&|\|\|)";
var results = Regex.Match(input, pattern)
    .Cast<Match>()
    .Select(m => m.Groups[1].Value)
    .ToList();

1
投票

简要

你可以使用下面的正则表达式,但我仍然强烈建议你为此编写一个合适的解析器,而不是使用正则表达式。


See regex in use here

\(((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!)))\)|&{2}|‌​\|{2}

Usage

See regex in use here

using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        string input = "((isoCode=s)||(isoCode=a))&&(title=s)&&((ti=2)&&(t=2))||(t=2&&e>5)";
        string pattern = @"\(((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!)))\)|&{2}|\|{2}";
        MatchCollection matches = Regex.Matches(input, pattern);
        foreach (Match match in matches)
        {
            Console.WriteLine(match.Groups[1].Success ? match.Groups[1].Value : match.Groups[0].Value);
        }
    }
}

结果

(isoCode=s)||(isoCode=a)
&&
title=s
&&
(ti=2)&&(t=2)
||
t=2&&e>5
© www.soinside.com 2019 - 2024. All rights reserved.