1

I need a method to split the string by alphanumeric characters,

Example-

String str = 'is this testing?yes it is.Please split the string, then use for further functionality.';

I need list of string as below as below,

is this testing

yes it is

Please split the string

then use for further functionality

Also i want to keep the record of characters by which it is split to construct the string back to the original

  • what does the fragment mean? I would like to change 'hey, there is ? a lot: of bits of, punctuation. here!!'; to 'Hey, There Is ? A Lot: Of Bits Of, Punctuation. Here!!'; – user41613 Feb 7 '17 at 23:10
1

I think you mean punctuation characters. I've picked a few that you might use for this example.

String hey = 'here is some stuff. Punctuation is the thing! Yes, split on that';
String[] strings = hey.split('[,.\\!\\:\\?]');
For (String s : strings){
    System.debug(s);
}

As you can see, the split expression is a regular expression. This is the reason for the escaping of these characters eg \\! in the expression.

To be able to reconstruct the string, you could use the strings array to replace matching strings in the source string with a token. Then when you want to reconstruct, just replace the tokens with the your phrases in the strings array.

For example:

String hey = 'hey, there is ? a lot: of bits of, punctuation. here!!';
System.debug(hey);

String[] strings = hey.split('[,.\\!\\:\\?]');
System.debug(strings);

//replace matched strings with empty
for (String fragment : strings ){
        hey = hey.replace(fragment,'__fragment__');
}

for (String fragment : strings){
    hey = hey.replaceFirst('__fragment__',fragment);
}
System.debug(hey);
  • did u read my last line "Also i want to keep the record of characters by which it is split to construct the string back to the original". i want to achieve that too. – snehakem Apr 15 '15 at 4:37
  • I did now. Tricky. I've added in an idea for how to do that. – Caspar Harmer Apr 15 '15 at 18:31
  • Did you see my suggestion for being able to recombine the strings back together? – Caspar Harmer Apr 17 '15 at 2:35
  • I didnt really get "To be able to reconstruct the string, you could use the strings array to replace matching strings in the source string. Then remove all whitespace and you should have a string that is just punctuation." – snehakem Apr 17 '15 at 4:34
  • Updated - the second example pulls apart the string and rebuilds it. – Caspar Harmer Apr 17 '15 at 8:22

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.