A regular expression is used to parse text that include '=' and put split string into a stringlist like key value pair.
But if value contains '=', it can not use list.add(key3+'='+'number=10');
key1 this's done
key2 that costs 10 dollars
key3 number=10 // invalid data, error prompt.
...
how to solve? Thank you.
Edit:
Thank you all for help.
If I have to add a string that includes '=' into key, how can I solve it?
for example, the text to be parsed 开发者_如何学Gomay be like this:
maleConsumer=john 1
maleConsumer=eric 2
femaleConsumer=mary 2
maleConsumer=john 8
...
I use regex reg='\b\S+\b' parse text and to put maleconsumer=john into key of stringlist, so that in stringlist, john's record will be:
maleConsumer=john 9 // maleconsumer=john is key, 9 is value
In such case, how can I do it?
Thank you all for your help again.
This works fine in Delphi
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.Add('key1=this''s done');
sl.Add('key2=that costs 10 dollars');
sl.Add('key3=number=10');
ShowMessage(sl.Values['key3']); // Displays number=10
finally
sl.Free;
end;
end;
This is better and still works
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.Values['key1'] := 'this''s done';
sl.Values['key2'] := 'that costs 10 dollars';
sl.Values['key3'] := 'number=10';
ShowMessage(sl.Values['key3']); // Displays number=10
finally
sl.Free;
end;
end;
BTW, you can specify the separator with TStringList.NameValueSeparator
Using NameValueSeparator to allow = in key
var
sl: TStringList;
begin
sl := TStringList.Create;
try
// Select a separater you are sure will never be used
sl.NameValueSeparator := '|';
sl.Values['maleConsumer=john'] := '1';
sl.Values['maleConsumer=eric'] := '2';
sl.Values['femaleConsumer=mary'] := '2';
sl.Values['maleConsumer=john'] := '8';
ShowMessage(sl.Values['maleConsumer=john']); // Displays 8
finally
sl.Free;
end;
end;
Check if the value contains '=':
if(value.indexOf('=') != -1){
//error prompt
}
Java:
you can use: String.contains() method.
For Delphi; you can set Delimiter and QuoteChar for your strings. Example:
cars := TStringList.Create;
// Now add some cars to our list - using the DelimitedText property
// with overriden control variables
cars.Delimiter := ' '; // Each list item will be blank separated
cars.QuoteChar := '|'; // And each item will be quoted with |'s
cars.DelimitedText := '|Honda Jazz| |Ford Mondeo| |Jaguar "E-type"|';
look here for detail.
Delphi:
var
LStringList: TStringList;
LStrValue: string;
begin
LStringList := TStringList.Create;
try
// set the value of a key
LStringList.Values['a key'] := 'a value';
// get the value of a key
LStrValue := LStringList.Values['a key'];
finally
FreeAndNil(LStringList);
end;// trye
end;
If you are using Delphi 2009 or later, use TDictionary instead of TStringList. That way you avoid all these hacks required to get TStringList to work properly.
精彩评论