Search code examples
groovy

I need to split a string and pass it to Array in Groovy


I have title names as string like this

string1 = "[G2.49.008][KT2.93.015] [TC-Pay-8.2.1.001_02] [TC-SAM-1.1.017_3][TC-Manage Dress-5.1.1.045_02] [TC-CAR-1.5.892_3] Customer able to find see his avatar"
string1 = "[G25.495.0058]  [KT2.93.015] Verify Create Account link is SSO"
string1 = "[V2.49.048][KT2.93.015][V4.9.04t] Check Paypal is available"  
string1 = "[P2.49.058] User generate OTP"

So whatever data comes, I need to cut the values coming in square bracket and add them to array. So expected output will be

array1 = ["G2.49.008", "KT2.93.015", "TC-Pay-8.2.1.001_02", "TC-SAM-1.1.017_3", "TC-Manage Dress-5.1.1.045_02", "TC-CAR-1.5.892_3"]
array1 = ["G25.495.0058", "KT2.93.015"]
array1 = ["V2.49.048", "KT2.93.015", "V4.9.04t"]
array1 = ["P2.49.058"]

Could you please help how can I get in this format. There is no fixed count that these many square bracket values will come. So how many ever comes, we needs to split and add them to array. Please help


Solution

  • You should probably go for Regular Expressions. Hope this helps:

    String string1 = "[G2.49.008][KT2.93.015] [TC-Pay-8.2.1.001_02] [TC-SAM-1.1.017_3][TC-Manage Dress-5.1.1.045_02] [TC-CAR-1.5.892_3] Customer able to find see his avatar"
    List array1 = (string1 =~/\[(.+?)\]/).findAll().collect { it[1].trim() }
    
    assert array1 == ["G2.49.008", "KT2.93.015", "TC-Pay-8.2.1.001_02", "TC-SAM-1.1.017_3", "TC-Manage Dress-5.1.1.045_02", "TC-CAR-1.5.892_3"]