1
votes

i need to extract string from a text as following example

Hi i have no name <z>empty</z>

i wanted to extract only text before <z> into array or string which is hi i have no name i tried this function

procedure Split (const Delimiter: Char; Input: string; const Strings: TStrings);
begin
   Assert(Assigned(Strings)) ;
   Strings.Clear;
   Strings.StrictDelimiter := true;
   Strings.Delimiter := Delimiter;
   Strings.DelimitedText := Input;
end;

but its only can split chars like ;,: etc.. i wanted to start split with this specific string <z>

4
If <z> is the sep, then empty</z> is the second string, right. Or do you need an XML parser. - David Heffernan
i wanted to read string before <z> kinda like string := Copy(Hi i have no name <z>empty</z>, 1, Pos('<z>', Hi i have no name <z>empty</z>)-1); - DelphiStudent
s := Copy(s,1,Pos('<z>',s)-1); you mean? - LU RD
Hope you're not going to parse HTML that way. - TLama

4 Answers

5
votes

As I read what you have written, you have a string and you want to ignore all text after the first occurrence of <z>. Use Pos and Copy for instance:

P := Pos('<z>', input);
if P = 0 then 
  output := input
else 
  output := Copy(input, 1, P-1);

Although something tells me that you really want an XML parser.

2
votes

Just an example using the string helper routines:

function CutString(const input,pattern: String): String;
var
  p: Integer;
begin
  p := input.IndexOf(pattern);
  if (p >= 0) then
    Result := input.Substring(0,p)
  else
    Result := input;
end;

var
  s: string;
begin
  s := 'Hi i have no name<z>empty</z>';
  s := CutString(s,'<z>');
  WriteLn(s);  // Outputs: 'Hi i have no name'
end.
1
votes

Here is a solution for the one-liner-fan, the crack-nuts-with-sledgehammer-lover, the regex-enthusiast, the waste-performance-ignorant and the xml-parser-grump:

TRegEx.Replace('Hi i have no name <z>empty</z>', '((^.*)(?=<z>)|(^.*)(?!<z>)).*', '$1');
0
votes

If the delimiter will be there for sure, you can do:

Result:= Copy(S, 1, Pos(Delimiter, S) - 1);

Otherwise user Davids answer or this (shorter but bad performance):

Result:= Copy(S, 1, Pos(Delimiter, S + Delimiter) - 1);