How to parse a regex pattern with regex

I want to use a regular expression to search for an unknown number of arguments in a string. I think that if I explain, it will be difficult, so let's just look at an example:

Regular expression: @ISNULL\('(.*?)','(.*?)','(.*?)'\)
String: @ISNULL('1','2','3')
Result:

Group[0] "@ISNULL('1','2','3')" at 0 - 20 
Group[1] "1" at 9 - 10 
Group[2] "2" at 13 - 14  
Group[3] "3" at 17 - 18  

This works great. The problem begins when I need to find an unknown number of arguments (2 or more).

What changes do I need to make for the regex to find all the arguments that will occur in the string?

So, if I parse this line "@ISNULL('1','2','3','4','5','6')", I will find all the arguments.

+3
source share
2 answers

, , . .NET Perl 6 .

#:

  string pattern = @"@ISNULL\(('([^']*)',?)+\)";
  string input = @"@ISNULL('1','2','3','4','5','6')";
  Match match = Regex.Match(input, pattern);
  if (match.Success) {
     Console.WriteLine("Matched text: {0}", match.Value);
     for (int ctr = 1; ctr < match.Groups.Count; ctr++) {
        Console.WriteLine("   Group {0}:  {1}", ctr, match.Groups[ctr].Value);
        int captureCtr = 0;
        foreach (Capture capture in match.Groups[ctr].Captures) {
           Console.WriteLine("      Capture {0}: {1}", 
                             captureCtr, capture.Value);
           captureCtr++; 
        }
     }
  }   

. , Java ( RegexBuddy):

:

Pattern regex = Pattern.compile("@ISNULL\\(('([^']*)',?)+\\)");
// or, using non-capturing groups: 
// Pattern regex = Pattern.compile("@ISNULL\\((?:'(?:[^']*)',?)+\\)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group();
} 

:

List<String> matchList = new ArrayList<String>();
try {
    Pattern regex = Pattern.compile("'([^']*)'");
    Matcher regexMatcher = regex.matcher(ResultString);
    while (regexMatcher.find()) {
        matchList.add(regexMatcher.group(1));
    } 
+2

, , . , :

'(\d)+?'

\d @ISNULL , , . + , , , ?, .

0

Source: https://habr.com/ru/post/1766728/


All Articles