I have a html formatted string:

s = "<span class=\"ads__unit__content__details\"> <span>Data I want to extract</span> </span> <p class=\"ads__unit__content__keys\"> \
<span>More data I want to extract</span> <span>Even more data I want to extract</span> </p> <p>"

I am trying to extract the different parts using a string pattern:

StringCases[s, "<span>"~~x__~~"</span>"-> x]

But this somehow just works on the outermost tag pairs. This is the resulting output:

    {"<span>Data I want to extract</span> </span> <p \class=\"ads__unit__content__keys\"> <span>More data I want to \
extract</span> <span>Even more data I want to extract</span>"}

Why does it ignore the


tags in the middle of the string? I would expect a list with all the substrings separated..

  • 2
    $\begingroup$ How about ImportString[s, "HTML"]? $\endgroup$ Sep 20, 2019 at 14:25
  • $\begingroup$ I have tried that @sjoerd-smit, but it gives me an error saying that the requested webpage needs javascript to function. Although I must admit it is weird because the string is displayed properly before trying to re-import it with ImportString.. $\endgroup$ Sep 20, 2019 at 21:08

1 Answer 1

StringCases[s, "<span>" ~~ Shortest[x___] ~~ "</span>" -> x]

{"Data I want to extract", "More data I want to extract", "Even more data I want to extract"}

Shortest >> Details:

  • If no explicit Shortest or Longest is given, ordinary expression patterns are normally effectively assumed to be Shortest[p], while string patterns are assumed to be Longest[p].
  • $\begingroup$ Thank you, that solved it. I was not aware of this option with patterns $\endgroup$ Sep 20, 2019 at 21:11

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.