简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM