7
$\begingroup$

I have a list of consisting of strings and string representation of numbers:

lis = {{"a (b) 1","c 2"},{"d 3","e f 4"}}

and need to split the elements so that the string representation of numbers are separated as follow:

res = {{{"a (b)","1"},{"c","2"}},{{"d","3"},{"e f","4"}}}

Am not sure how to come up with the necessary pattern for StringSplit Thanks for ideas.

$\endgroup$
10
$\begingroup$
StringSplit[#, WhitespaceCharacter... ~~ n : NumberString :> n] & /@ lis

{{{"a (b)", "1"}, {"c", "2"}}, {{"d", "3"}, {"e f", "4"}}}

$\endgroup$
  • $\begingroup$ that was fast! thank you. $\endgroup$ – Suite401 Sep 21 at 2:18
1
$\begingroup$

Here's an equivalent to kglr's solution, using replacement and regex:

{{"a (b) 1", "c 2"}, {"d 3", "e f 4"}} /. 
s_String :> StringCases[s, RegularExpression["(.+) (\\d)$"] :> Sequence["$1", "$2"]]
   {{{"a (b)", "1"}, {"c", "2"}}, {{"d", "3"}, {"e f", "4"}}}
$\endgroup$

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.