Search code examples
delphi

Delphi: Advanced string search commands


Kenneth is a string. Let's say it contains 'justabcsome123texthaha'.

I know this already:

To find text:

if(pos('bcsome12',Kenneth) > 0) then

To check length:

if(Length('Kenneth') > 10) then

Question 1:

I want to find 'texthaha', but only if it is at the end of the string.

if(pos('texthaha',Kenneth) > 0) then

Sadly this will find it anywhere, even if it is in the middle. Is there a simple way?

Question 2:

Is there a simple way to do a search, but with a * (any character in between)?

For example, if I want to search for bcsome1*3text and I don't care what character the * is. I think it's called a wildcard, isn't it?

if(pos('bcsome1'*'3text',Kenneth) > 0) then

I know the above doesn't work. but is there a similar way? Edit: Might be of importance: **Delphi version used is very old, not sure of the version, but it's from year 2006.


Solution

  • There are functions EndsStr() and EndsText() (the latter is case-insensitive) in the StrUtils unit

    But, you easily could provide the needed functionality with known functions (Pos also has an overloaded version with the third parameter in fresh Delphi):

    NPos =  Length(S) - Length(Sub) + 1;
    if PosEx(Sub, S, NPos) = NPos then...
    

    or variant proposed by @Sertac Akyuz:

    if Copy(S, NPos, Length(Sub)) = Sub ...
    

    The second problem might be solved with function like MatchesMask()

     if MatchesMask(Kenneth, '*bcsome1*3text*')...