【问题标题】:Regexp & back references正则表达式和反向引用
【发布时间】:2011-01-11 21:58:13
【问题描述】:

伙计们 我需要帮助从字符串中提取

“AAA、BBB”、“CCC”、DDDD

以下组:

  1. AAA, BBB
  2. CCC
  3. DDDD

是否可以通过正则表达式提取三个组,如果可以,那么如何提取?

谢谢。

【问题讨论】:

  • 这些引号会一直按那个顺序出现吗?
  • 使用什么编程语言/工具?
  • DDDD之前应该有引号吗?
  • 2BoltClock:规则很简单。用逗号分隔的单词,如果 term 包含多个单词,它们可以在配额中。但术语可以包含配额,例如:toys 'r' us。
  • 所以这是 CSV?我会推荐一个特定的 CSV 解析器,例如 codeproject.com/KB/database/CsvReader.aspx

标签: .net regex


【解决方案1】:

函数

public void RunTest()
{
    const string toTest = "\"AAA, BBB\", \"CCC\", \"DDDD\"";
    var exp = new Regex("\G(?:^|,)\s*\"([^\"])\"");
    var matches = exp.Matches(toTest);
    foreach (var match in matches.Cast())
    {
        Console.WriteLine(@"Matched expression: {0}", match);
        foreach (var group in match.Groups.Cast())
        {
            Console.WriteLine(@"Matched group: {0}", group);
        }
    }
}
将返回
Matched expression: "AAA, BBB"
Matched group: "AAA, BBB"
Matched group: AAA, BBB
Matched expression: , "CCC"
Matched group: , "CCC"
Matched group: CCC
Matched expression: , "DDDD"
Matched group: , "DDDD"
Matched group: DDDD
所以每隔一组收集一次,你就会得到我想你想要的。 请注意,我在您的 DDDD 周围添加了双引号。我以为那是一个错字。 如果不是错字,您可以尝试正则表达式:
var exp = new Regex("\G(?:^|,)(?:\s(?:\"([^\"])\")|([^\",]))");

说明:

\G The match must occur at the point where the previous match ended.
[^"] Any character except the double quote
\s Any whitespace
* zero or more occurrences of the preceding element
( and ) define a group
(?: defines a noncapturing group
希望有帮助:)

【讨论】:

    【解决方案2】:

    var delimiterPattern = @",(?=(?:[^\"]\"[^\"]\")(?![^\"]\"))"; var parts = string.Split(delimiterPattern);

    对于字符串:toys "r" us", "AAAA", "toys "r" us","toys ,r,","toys ,"r",",test

    将返回: 1.“玩具反”我们 2.“AAAA” 3.《玩具反斗城》 4.“玩具,r” 5.“玩具”,“r”, 6. 测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多