8
$\begingroup$

I have a nested list consisting of strings. Each string has a non-numeric part and a part with a string representation of numbers.

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

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

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

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

$\endgroup$

3 Answers 3

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

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

$\endgroup$
1
  • $\begingroup$ that was fast! thank you. $\endgroup$
    – Suite401
    Sep 21, 2019 at 2:18
2
$\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$
1
$\begingroup$

Essentially a copy of J.M.'s answer using StringExpression:

Clear["Global`*"];
lis = {{"a (b) 1", "c 2"}, {"d 3", "e f 4"}};

sc = StringCases[#, 
    StartOfString ~~ b : Shortest[___] ~~ k : NumberString :> 
     Sequence @@ {StringTrim@b, k}] &;

Map[sc, lis]

{{{"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 and acknowledge you have read our privacy policy.

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