Home > Mobile >  Ignore regex separator between "display name"
Ignore regex separator between "display name"

Time:09-10

I need to split the string with the separator ">," but this separator is allowed between the "" that correspond to the display name e.g:

""display>, name>," <[email protected]>, "<display,> >" <[email protected]>";

I need it to be separated like:

[["display>, name>," <[email protected]>,] ["<display,> >" <[email protected]>"]]

I'm using at this moment this:

aux = Regex.Split(addresses, @"(?<=\>,)");

But this doesnt work when the display name has ">,"

E.g str:

str = "\"Some name>,\" <[email protected]>, \"<display,> >\" <[email protected]>'";

CodePudding user response:

You can use

var matches = Regex.Matches(str, @"""([^""]*)""\s*<([^<>]*)>")
    .Cast<Match>()
    .Select(x => new[] { x.Groups[1].Value, x.Groups[2].Value })
    .ToArray();

See the C# demo:

var p = @"""([^""]*)""\s*<([^<>]*)>";
var str = "\"Some name>,\" <[email protected]>, \"<display,> >\" <[email protected]>'";
var matches = Regex.Matches(str, p).Cast<Match>().Select(x => new[] { x.Groups[1].Value, x.Groups[2].Value }).ToArray();
foreach (var pair in matches)
    Console.WriteLine("{0} : {1}", pair[0],pair[1]);

Output:

Some name>, : [email protected]
<display,> > : [email protected]

See also the regex demo. Details:

  • " - a " char
  • ([^"]*) - Group 1: any zero or more chars other than "
  • " - a " char
  • \s* - zero or more whitespaces
  • < - a < char
  • ([^<>]*) - Group 2: any zero or more chars other than < and >
  • > - a > char
  • Related