Extracting data between two consistents in a string

Hello all

Here is the data in the field:

9 875 300 20 418002879539 21 06/28/2024 22 QT 451 OUTSIDE PHOENIX AZ 23 64890 64 00:01:49 0

I am able to extract the bold data in this example using a substring case statement:
When REPLACE(REPLACE(REPLACE(LTRIM(SUBSTRING(ah.TokenString,70,2)),CHAR(0x09),''),CHAR(0x04),''),CHAR(0X05),'') = '23' AND REPLACE(REPLACE(REPLACE(LTRIM(SUBSTRING(ah.TokenString,79,2)),CHAR(0x09),''),CHAR(0x04),''),CHAR(0X05),'') = '64' AND Left(ah.TokenString,1) = '9' AND ah.TransactionType In ('VPA','VCA','VCR') Then REPLACE(REPLACE(REPLACE(LTRIM(SUBSTRING(ah.TokenString,73,5)),CHAR(0x09),''),CHAR(0x04),''),CHAR(0X05),'')

Although the data that I'm trying to retrieve is always between the 23 and the 64, it's not always in the same spot.

How can I just extract the data between the 23 and 64 regardless of where it's at in the string?
Thanks.


DECLARE @string varchar(8000);
DECLARE @string2 varchar(8000);
SET @string = '9 875 300 20 418002879539 21 06/28/2024 22 QT 451 OUTSIDE PHOENIX AZ 23 64890 64 00:01:49 0'
SET @string2 = '9 875 300 20 418002879539 21 06/28/2024 22 QT 451 OUTSIDE PHOENIX AZ 23 64890'

SELECT string, result
FROM ( SELECT @string AS string UNION ALL SELECT @string2 ) AS strings
CROSS APPLY (
    SELECT CHARINDEX('23 ', string) AS start_of_substring, CHARINDEX('64 ', string + ' ') AS end_of_substring
) AS ca1
CROSS APPLY (
    SELECT LTRIM(RTRIM(CASE WHEN start_of_substring = 0 THEN '' ELSE SUBSTRING(string, start_of_substring + 3, 
        CASE WHEN end_of_substring = 0 THEN LEN(string) - start_of_substring + 3 ELSE end_of_substring - (start_of_substring + 3) END) END)) AS result
) AS ca2

CHARINDEX('23 ', string)

Should use <space>23<space> instead or it might failed on string with year 2023