substringampscript

Using AMPScript to extract text from a String after nth delimiter


I need to be able to extract from a string after nth delimiter. In this case, the delimiter is an underscore.

The challenge is that the last delimiter could be in the 2nd, 3rd,4th or 5th position

Example:

  1. LB_AB_BookingReminder_123-1-2-1S (3rd position)

  2. LB_AB_123-1-2-1S (2nd position)

  3. LB_AB_Booking_Reminder_123-1-2-1S (4th position)

Output Needed: 123-1-2-1S

Thank You


Solution

  • Using the RegExMatch() function may be your best bet:

    %%[
    
    set @pattern = "^.+_(.+\-\d+\-\d+\-.+)"
    set @s1 = "LB_AB_BookingReminder_123-1-2-1S"
    set @s2 = "LB_AB_BookingReminder_123-1-2-1S"
    set @s3 = "LB_AB_Booking_Reminder_123-1-2-1S"
    
    set @match1 = RegExMatch(@s1, @pattern, 1)
    set @match2 = RegExMatch(@s2, @pattern, 1)
    set @match3 = RegExMatch(@s3, @pattern, 1)
    
    ]%%
    <br>%%=v(@match1)=%%
    <br>%%=v(@match2)=%%
    <br>%%=v(@match3)=%%
    

    Output:

    123-1-2-1S
    123-1-2-1S
    123-1-2-1S
    

    Regex101 snippet: https://regex101.com/r/DJeKjd/1

    AMPscript tester: https://mcsnippets.herokuapp.com/s/F4WISQvc