【问题标题】:Regex get text between parentheses and keywords正则表达式获取括号和关键字之间的文本
【发布时间】:2014-04-04 14:58:52
【问题描述】:

我有这样的文本模式;

(((a) or (b) or (c)) and ((d) or (e)) and ((!f) or (!g)))

我想这样得到它;

((a) or (b) or (c))
((d) or (e))
((!f) or (!g))

之后我想像这样把它们分开;

a,b,c
d,e
!f,!g

任何帮助都会很棒:)

编辑 1: 对缺少的部分感到抱歉;使用语言是 C#,这就是我得到的;

(\([^\(\)]+\))|([^\(\)]+)

我得到了;

(a) or (b) or (c) and (d) or (e) and (!f) or (!g)

已经谢谢了!

【问题讨论】:

  • 你使用什么语言?
  • 尝试自己编写一些东西,如果不起作用,请具体向我们展示您所做的事情,以便我们为您提供帮助。您启动它,我们提供帮助。我们不是为你写的。向我们展示您尝试过的实际代码,然后描述发生的事情和不正确的事情,然后我们可以从那里帮助您。如果您先自己尝试一下,您可能会非常接近答案。
  • 抱歉遗漏了:)
  • 我认为没有正则表达式可能更容易做到这一点
  • 嵌套元素和正则表达式,天哪。

标签: regex text keyword parentheses


【解决方案1】:

this previous regex 并稍微修改代码...

string msg= "(((a) or (b) or (c)) and ((d) or (e)) and ((!f) or (!g)))";
var charSetOccurences = new Regex(@"\(((?:[^()]|(?<o>\()|(?<-o>\)))+(?(o)(?!)))\)");
var charSetMatches = charSetOccurences.Matches(msg);
foreach (Match mainMatch in charSetMatches)
{
    var sets = charSetOccurences.Matches(mainMatch.Groups[1].Value);
    foreach (Match match in sets)
    {
        Console.WriteLine(match.Groups[0].Value);
    }
}

第一个正则表达式用于获取最外层括号的内容。

然后使用相同的正则表达式来获取“更大”内容中的各个集合。你得到这个作为输出:

((a) or (b) or (c))
((d) or (e))
((!f) or (!g))

ideone demo

如果你想删除外括号,只需更改最里面的一行:

Console.WriteLine(match.Groups[0].Value);

Console.WriteLine(match.Groups[1].Value);

获得:

(a) or (b) or (c)
(d) or (e)
(!f) or (!g)

我相信你可以从这里拿走它。

【讨论】:

  • 谢谢你!我刚看到你的答案,这也可以!我也会用我的答案更新我的问题:)
【解决方案2】:

在我工作之后,我想到了这个;

  string msg = "(((a) or (b) or (c)) and ((d) or (e)) and ((!f) or (!g)))";

  Regex regex = null;
  MatchCollection matchCollection = null;

  regex = new Regex(@"(\([^\(\)]+\))|([^\(\)]+)"); // For outer parantheses
  matchCollection = regex.Matches(query);
  foreach (Match match in matchCollection)
  {
    MatchCollection subMatchCollection = Regex.Matches(match.Value, @"(""[^""]+"")|([^\s\(\)]+)"); // For value of inner parantheses
    foreach (Match subMatch in subMatchCollection)
    {
      //with 2 loops i got each elements of this type of string.
    }
  }

感谢大家! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 2020-06-03
    • 2019-01-20
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    相关资源
    最近更新 更多