如何為重復模式生成正則表達式

[英]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