Get First word that contains numbers

后端 未结 5 716
醉梦人生
醉梦人生 2021-01-22 18:58

Anyone can help with how can I find the first full Word that contains numbers? I have an adress, for example:

procedure TForm1.Button4Click(Sender: TObject);
var         


        
5条回答
  •  耶瑟儿~
    2021-01-22 19:43

    You can use Regular Expressions to accomplish this task:

    const
      CWORDS = 'Saint Steven St 6.A II.f 9';
      CPATTERN = '([a-zA-z\.]*[0-9]+[a-zA-z\.]*)+';
    
    var
      re: TRegEx;
      match: TMatch;
    
    begin
      re := TRegEx.Create(CPATTERN);
      match := re.Match(CWORDS);
      while match.Success do begin
        WriteLn(match.Value);
        match := match.NextMatch;
      end;
    end.
    

    The above prints:

    6.A
    9


    To get the very first word containing numbers, like your question requires, you may consider to add a function to your code:

    function GetWordContainingNumber(const AValue: string): string;
    const
      CPATTERN = . . .;//what the hell the pattern is
    var
      re: TRegEx;
      match: TMatch;
    begin
      re := TRegEx.Create(CPATTERN);
      match := re.Match(AValue);
      if match.Success then
        Result := match.Value
      else
        Result := '';
    end;
    

    The newly added function can be called like this:

    showmessage(GetWordContainingNumber(SourceString));
    

提交回复
热议问题