pipsik
pipsik

Reputation: 219

Whats wrong in my regex pattern?

I'm wrote a pattern

string pattern2 = @"(?[<ports>\w+,*]*)";

This pattern should help parse string of next format

[port1, port2_4][portN_][port,port2,port5,p0_p1]

After parsing I'm want to have array of strings:

1. port1, port2_4
2. portN_
3. port, port2,port5,p0_p1

Upvotes: 1

Views: 66

Answers (1)

Keith Nicholas
Keith Nicholas

Reputation: 44288

this will work...

(?<=\[)(?<ports>.*?)(?=\])
  • (?<=\[) prefix of [ but dont include in match
  • (?<ports>.*?) named capture "ports" match anything non greedy ( as little as possible)
  • (?=\]) suffix of ] but don't include it in the match

code :-

Regex regex = new Regex(@"(?<=\[)(?<ports>.*?)(?=\])");
var m = regex.Matches("[port1, port2_4][portN_][port,port2,port5,p0_p1]");
foreach (var p in m)
{
    Console.WriteLine(p);
}

output :

port1, port2_4
portN_
port,port2,port5,p0_p1

Upvotes: 2

Related Questions