5
$\begingroup$

My question is similiar to previous questions (see here or here), although the issue is maybe somewhat more complicated:

I have a list with strings like this:

list = {{"text1, text2, 2003, text3"},{"text1, 1994, text2"},{text1, text2, text3 2014, text4}}

I now want to extract the part of the string which contains the 4-digit Number (or in this case its a year number) AND is separated by the commas so that the outcome is:

{{"2003"},{"1994"},{"text3 2014"}}

I have tried this one:

StringCases[#,", " ~~ w : (___ ~~ Repeated[DigitCharacter, {4}]) ~~ ", " :> w] & /@ list

but this extracts always the part from the first comma in each string

many thanks for you suggestions

$\endgroup$
2
  • $\begingroup$ @user1066: I dont understand your question, but the answer by kglr seems to solve it! $\endgroup$
    – M.A.
    Sep 2 at 12:49
  • $\begingroup$ @user1066 thx for that hint! I have edited the post. $\endgroup$
    – M.A.
    Sep 2 at 13:09
3
$\begingroup$

The proposal in the original question can be made to work by replacing ___ with Except[","]...:

StringCases[", "~~w:(Except[","]...~~Repeated[DigitCharacter, {4}])~~", " :> w] /@ list

(* {{"2003"}}, {{"1994"}}, {{"text3 2014"}} *)
$\endgroup$
5
$\begingroup$
Map[StringTrim @* Select[StringContainsQ @ Repeated[DigitCharacter, {4}]]] @
 StringSplit[Flatten @ list, ","]
{{"2003"}, {"1994"}, {"text3 2014"}}

You can replace Select[...] with Cases[_?(StringContainsQ@Repeated[DigitCharacter, {4}])] to get the same result.

$\endgroup$
4
$\begingroup$
StringCases[#, RegularExpression["([^,]+[\\d]{4})"]:> StringTrim["$1"]]&/@list//Catenate

(* {{2003}, {1994}, {text3 2014}} *)

where:

list = {{"text1, text2, 2003, text3"},{"text1, 1994, text2"},{"text1, text2, text3 2014, text4"}}
$\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.