0

Can anyone help me how to get the id of the case on this string?

String caseID = '500k000000gcuyciad&notify=1';

I dont want to include the &notify=1 or &notify=2 and so on

2

You can use String.split(regExp) here.

You just need to perform something as:

String caseID = '500k000000gcuyciad&notify=1';
List<String> splitString = caseId.split('&');
String newCaseId = splitString.get(0); // the first item in the list is the Id

OR

(Adding from the comment) If you always know that the first occurrence in your string will be always the Id, you can use this approach as well:

String newCaseId = caseId.substringBefore('&');

There are other methods as well which can be used based on the use case. You can take a look at details on the methods available in the String class on its documentation.

2
  • Or String.substringBefore. The reason I avoided this approach is, you might not know the ordering will be consistent. – Adrian Larson Dec 7 '18 at 14:21
  • That's correct. It was more of a direct answer to the question with the simplest approach, which I have used in past, not only to substring but in general to split string based on a regex. – Jayant Das Dec 7 '18 at 14:23
4

The String class documentation has a lot of methods for manipulating strings.

Of those, the left() method, the split() method, or the replaceAll() method are the first that come to mind that would assist you here.

  • Since you know you're looking for an Id (which is either 15 or 18 characters long), left(15) or left(18) would return your Id
  • In your example, there is a character (the ampersand "&") that divides the substring you want from the substring you don't. split('&') would give you an array, and the first element (index 0) would contain your id
  • Similar to Adrian's approach, replaceAll('(\\w{15}|\\w{18})*', '$1') would find your 15 or 18 character Id, place it into a capturing group, match the entire rest of the string, and cause the entire string to be replaced with just your target Id

There are likely more ways to skin this particular cat.

2

If you are trying to find just the Case Id, I recommend you use a regular expression looking for 500 (the key prefix) followed by 15 word characters.

String input = '500k000000gcuyciad&notify=1';
Matcher m = Pattern.compile('500\\w{15}').matcher(input);
String caseId = m.find() ? m.group() : null;