I'm trying to parse given string which is kind a of path separated with /
. I need to write regex that would match each segment in the path to corresponding regex group.
Example 1:
input:
/EAN/SomeBrand/appliances/refrigerators/RF444
output:
Group: producer, Value: SomeBrand Group: category, Value: appliances Group: subcategory, Value: refrigerators Group: product, Value: RF4441
Example 2:
input:
/EAN/SomeBrand/appliances
output:
Group: producer, Value: SomeBrand Group: category, Value: appliances Group: subcategory, Value: Group: product, Value:
I tried following code, it works fine when the path is full (like in the first exmaple) but fails to find the groups when the input string is impartial (like in example 2).
static void Main()
{
var pattern = @"^" + @"/EAN"
+ @"/" + @"(?<producer>.+)"
+ @"/" + @"(?<category>.+)"
+ @"/" + @"(?<subcategory>.+)"
+ @"/" + @"(?<product>.+)?"
+ @"$";
var rgx = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
var result = rgx.Match(@"/EAN/SomeBrand/appliances/refrigerators/RF444");
foreach (string groupName in rgx.GetGroupNames())
{
Console.WriteLine(
"Group: {0}, Value: {1}",
groupName,
result.Groups[groupName].Value);
}
Console.ReadLine();
}
Any suggestion is welcome. Unfortunately I cannot simply split the string since the framework I'm using expects regex object.
Try
var pattern = @"^" + @"/EAN"
+ @"(?:/" + @"(?<producer>[^/]+))?"
+ @"(?:/" + @"(?<category>[^/]+))?"
+ @"(?:/" + @"(?<subcategory>[^/]+))?"
+ @"(?:/" + @"(?<product>[^/]+))?";
Note how I replaced the .
with [^/]
, because you want to use the /
to split strings. Note even the use of the optional quantifier for each sub-part (?
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments