+ Start a Discussion
Monishan MMonishan M 

How to get a specified value from string


I have below values in a string

String s1 = ' __valuesE-123456yes__'
String s2 = '__values2E-234567fail__'

I need to fetch only the values starting from 'E- to the next 6 digit values from the strings
Ouptut should be like : E-123456

Can you please let me know how to achieve this?

Janet EpebinuJanet Epebinu

Hi Monishan,
Use the substring(startIndex, endIndex), stating the start index and the end index.

For String s1 = ' __valuesE-123456yes__'; 
System.debug('Result: '+ s1.substring(8, 16));

!) There is a space between the apporstrophe and the first underscore. So I deleted it. That is why the starting index is 8 and the end index is 16. If you don't want ot delete the white space, then the starting index will be 9
2) I executed the snippet on Anonymous window and got the result below:
    USER_DEBUG [2]|DEBUG|Result: E-123456
3) Use the same method for the second one.
For more information, go to:

Please, let me know if this helps you

Hi Monishan,

If you've some specific string formats like this, and looking to get the sub string starting with "E-", it'll be better to first find the index of "E-" in the original string and then get the required substring starting from that index.

Here is a working code for example:
String s1 = '__valuesE-123456yes__';
String s2 = '__values2E-234567fail__';

Integer index1 = s1.indexOf('E-');
Integer index2 = s2.indexOf('E-');
System.debug(s1.substring(index1, index1+8));
System.debug(s2.substring(index2, index2+8));