I have requirement to get the string by splitting right side Ex 1.abc-sgd-ajj-test output needs to be in string = abc-sgd

test-string-split-exam-demo output needs to be in string = test-string-split

I have tried

String str = 'this-is-test-data'; List res = str.split('-', 2); System.debug(res);

but not sure how i can check from right to left and after second underscore i need remaining string in to variable can someone please suggest

  • Do you need String.split, or do you just need a solution?
    – sfdcfox
    Aug 23, 2021 at 15:56
  • I need to get the out put like below examples. Test-string-split-exam-demo o/p = test-string-split
    – Sandy
    Aug 23, 2021 at 15:58
  • test-string-split-exam-demo o/p = test-string-split
    – Sandy
    Aug 23, 2021 at 15:58
  • which will be in string only ..which i wil use for further ioperation ,but not able to extract it.I need to check from right hand side 2 hypens and whatever is coming before that i need to take that out
    – Sandy
    Aug 23, 2021 at 15:59

1 Answer 1


This is arguably much easier with a Regular Expression:

Pattern p = Pattern.compile('(.+?)(-\\w+){2}$');
String input = 'test-string-split-exam-demo';
Matcher m = p.matcher(input);

Where the first part (.+?) is what we want to match, and the last part (-\\w+){2}$ is what we want to ignore. Finally, group(1) gives us the first capture group, the part we wanted.

  • awsome.its working.thanks sfdcfox. Also i requst you ,can you just provide some guidance from where i can learn regex part or regular expression stuffs
    – Sandy
    Aug 23, 2021 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.