Reputation: 49
I am no good with RegEx so not real familiar with what is going on in this code I borrowed. I want to split the following String:
CHARM CARD_SLOT=1 IO_SUBSYSTEM="CHARMS" CONTROLLER="CIOC-CB3-IO" DEFINITION="CHMIO_DO_24_VDC_HIGH-SIDE_CHARM"
So that is in individual strings like: (What I want to return)
CHARM CARD_SLOT=1
IO_SUBSYSTEM="CHARMS"
CONTROLLER="CIOC-CB3-IO"
DEFINITION="CHMIO_DO_24_VDC_HIGH-SIDE_CHARM"
I am using this code:
while (null != (workString = s.ReadLine()))
{
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"((""((?<token>.*?)(?<!\\)"")|(?<token>[\w]+))(\s)*)", options);
var result = (from Match m in regex.Matches(workString)
where m.Groups["token"].Success
select m.Groups["token"].Value).ToList();
foreach (string o in result)
{
if (!o.Contains("{") || !o.Contains("}"))
{
endResult = endResult + "\r\n" + o;
Console.WriteLine("'{0}'", "\r\n" + o);
}
}
}
What I am currently returning
CHARM
CARD_SLOT
1
IO_SUBSYSTEM
CHARMS
CONTROLLER
CIOC-CB3-IO
DEFINITION
CHMIO_DO_24_VDC_HIGH-SIDE_CHARM
Upvotes: 1
Views: 65
Reputation: 108
this pattern should work:
pattern = @"[^=]+=[^=]+(\s|.$)"; //matches with spaces
pattern = @"[^=\s]+=[^=]+(?=(\s|.$))"; //matches without spaces
my idea is to take =
and "look around" on both sides (especially right side).
In both pattern I look whether it ends with " " or it is very end of string. And finally I remove matched spaces by using lookahead feature as we don't need them.
Upvotes: 0
Reputation: 26917
This matches your example:
var pattern = @"(\w[\w ]+=(?:""[^""]+""|[^ ]+))+";
var optionsList = Regex.Matches(src, pattern).Cast<Match>().Select(m => m.Value).ToList();
Upvotes: 1