如何为重复模式生成正则表达式

[英]How do I generate regex for repeating pattern


Good day! I am working on an interpreter of LOLCODE and I'm having a trouble in this line:

美好的一天!我正在研究LOLCODE的翻译,我在这方面遇到了麻烦:

SMOOSH "A" AN "B" AN "C" AN "D"

I need to get the string literals A,B,C,D but I only got the first and the last two literals.

我需要得到字符串文字A,B,C,D,但我只得到第一个和最后两个文字。

Here's my code:

这是我的代码:

 r = new Regex(@"(\s+)?(?<smoosh>SMOOSH)\s+(\""(?<yarn1>[^\""]+).*)\s+(\""(?<yarn2>[^\""]+).*)(\s+)?((\s+)(AN)?(\""(?<yarn3>[^\""]+).*))+(\s+)?(?<comment>BTW\s*.*\s*)?$");

I need to hold all the string literals so that i could concatenate it later. Thanks in advance.

我需要保存所有的字符串文字,以便我以后可以连接它。提前致谢。

2 个解决方案

#1


1  

Try this:

尝试这个:

Regex re = new Regex(@"""(.*?)""");
MatchCollection mc = re.Matches(sourcestring);
      int mIdx=0;
      foreach (Match m in mc)
       {
        for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
          {
            Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
          }
        mIdx++;
      }

You will get all literals in array.

您将获得数组中的所有文字。

#2


0  

You could use capturing groups.

您可以使用捕获组。

@"""([^""]*)"""

And get the string you want from group index 1.

并从组索引1中获取所需的字符串。

Regex rgx = new Regex(@"""([^""]*)""");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[1].Value);

OR

要么

Use \G anchor.\G assert position at the end of the previous match or the start of the string for the first match. It grabs the values inside double quotes only on the lines which contains the string SMOOSH

使用\ G anchor。\ G在前一个匹配结束时断言位置或在第一个匹配的字符串开头处断言。它仅在包含字符串SMOOSH的行上抓取双引号内的值

@"(?:(?:\s+)?(?<smoosh>SMOOSH)\s+|(?<!^)\G) *(?:AN)* *""?([^""\n]*)""?"

Code:

码:

String input = @"SMOOSH ""A"" AN ""B"" AN ""C"" AN ""D""";
Regex rgx = new Regex(@"(?:(?:\s+)?(?<smoosh>SMOOSH)\s+|(?<!^)\G) *(?:AN)* *""?([^""\n]*)""?");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[1].Value);

IDEONE

IDEONE


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/12/08/7deee64cb15fdf6195b22aa7c64929a8.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com