1

I want to grab value after one regex is passed. The sample is

My test string is ##[FirstVal][SecondVal]##

I want to grab FirstVal and SecondVal.

I have tried \#\#(.*?)\#\# pattern but only return [FirstVal][SecondVal].

Is it possible to evaluate result of one regex and apply another regex?

Manprit Singh Sahota
  • 1,279
  • 2
  • 14
  • 37

2 Answers2

1

In .NET, you may use a capture stack to grab all the repeated captures.

A regex like

##(?:\[([^][]*)])+##

will find ##, then match and capture any amount of strings like [ + texts-with-no-brackets + ] and all these texts-with-no-brackets will be pushed into a CaptureCollection that is associated with capture group 1.

See the regex demo online

enter image description here

In C#, you would use the following code:

var s = "My test string is ##[FirstVal][SecondVal]##";
var myvalues = Regex.Matches(s, @"##(?:\[([^][]*)])+##")
        .Cast<Match>()
        .SelectMany(m => m.Groups[1].Captures
          .Cast<Capture>()
          .Select(t => t.Value));
 Console.WriteLine(string.Join(", ", myvalues));

See the C# demo

Mind you can do a similar thing with Python PyPi regex module.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

It will make a difference as to what programming language you are using as the modules might vary slightly. I used python for my solution, since you didn't specify what language you were using, and you could use two parentheses with the #'s on either side and using an escape character to make regex not match the square braces (ie. \[(\w+)\]. Where in the python re module the \w represents the denotation for a-zA-Z0-9_.

import re
data = "##[FirstVal][SecondVal]##"
x = re.search(r'##\[(\w+)\]\[(\w+)\]', data)
print(x.groups())

Which prints ('FirstVal', 'SecondVal')

avlec
  • 396
  • 1
  • 15