I have a string which looks like:
(Service=[MyCar]&(Type=[News]|Type=[Review]))
I need to get the values of Type, there could be 1 type or multiple types.
My current regular expression is:
/Type=[(News|Review|Video)]*/g
It doesn't return me the values, instead it returns "Type="
The square brackets []
have a special meaning in regex, so they need to be escaped:
Type=\[(News|Review|Video)\]
Compare this
With this
In the first case you are actually matching a single character in the list (News|RviVdo)
with [(News|Review|Video)]
For each match, you will find the text you are looking for in Group[1]
Use MatchCollection
and prefix brackets []
with a backslash \\
string input = "(Service=[MyCar]&(Type=[News]|Type=[Review]))";
string pattern = @"Type=\[(News|Review|Video)\]";
MatchCollection matches = Regex.Matches(input, pattern);
foreach(Match match in matches)
{
foreach(Group group in match.Groups)
{
Console.WriteLine(group);
}
}
A pattern like this
Type=[(\\w*)]
will give you the groups. You can look at the expression here . Also you can test this C# code at dotnetfiddle
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input = "(Service=[CarSales]&(Type=[News]|Type=[Review]))";
string pattern = @"Type=\[(\w*)\]";
MatchCollection matches = Regex.Matches(input, pattern);
foreach(Match match in matches)
{
Console.WriteLine(match.Groups[1].Value);
}
}
}
You can find some information about the groups and the index on the MSDN "Match.Groups Property" page.
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.