Reputation: 59
I currently have a problem in my script. I just want to show some parts with Regex.
string str = "db_name=Killa db_type=0 db_sync=false db_id=12 db_status=offline|db_name=mcHD db_type=0 db_sync=true db_id=28 db_status=online|db_name=sla db_type=0 db_sync=false db_id=193 db_status=online";
var l = string.Join("|", str);
var reg = Regex.Matches(l, @"db_name=(.+?)\s+db_id=(\d+)\s+db_status=(.+?)").Cast<Match>().Select(a => new
{
db_name = a.Groups[1].Value,
db_id = a.Groups[2].Value,
db_status = a.Groups[3].Value
}).ToList();
foreach (var x in reg)
{
Console.WriteLine(x.db_name + " " + x.db_id + " " + x.db_status);
}
But this does not give what I want back, but this data.
Killa db_type=0 db_sync=false 12 o
mcHD db_type=0 db_sync=true 28 o
sla db_type=0 db_sync=false 193 o
And that's what I want:
Killa 12 offline
mcHD 28 online
sla 193 online
I hope I get an answer and thanks for the help.
Upvotes: 2
Views: 70
Reputation: 7142
You can use the following solution:
var list =
from z in str.Split('|')
let x = z.Split(' ')
let p1 = x[0].Split('=')[1]
let p2 = x[3].Split('=')[1]
let p3 = x[4].Split('=')[1]
select string.Join(' ', p1, p2, p3);
Upvotes: 0
Reputation: 26782
Your regex does exactly what you tell it to do:
@"db_name=(.+?)\s+db_id=(\d+)\s+db_status=(.+?)"
This takes everything between db_name
until the space before db_id
. But in the input string, you have also db_type an db_sync between those 2 fields.
If you change to this regex, it works like you want:
@"db_name=(?<name>.+?)\s+db_type=(?<type>\d+)\s+db_sync=(?<sync>true|false)\sdb_id=(?<id>\d+)\s+db_status=(?<status>[^|]+)"
This also captures db_type and db_sync, so you have to adjust your code to
db_name = a.Groups[1].Value,
db_id = a.Groups[4].Value,
db_status = a.Groups[5].Value
Or, since I used named groups:
db_name = a.Groups["name"].Value,
db_id = a.Groups["id"].Value,
db_status = a.Groups["status"].Value
However. I seriously doubt that this is the proper way to solve your underlying problem. Where does the original data come from? Why are you using regular expressions?
Upvotes: 1
Reputation: 1052
You can change your regex to
db_name=(\w+)[^|]+db_id=(\d+)[^|]+db_status=(\w+)
And will get what you want
Upvotes: 1