I'm trying to extract a specific part of a long string, where the part of interest starts with "testx" and ends with a number before an underscore follows, so e.g., "abcd_xt_testx1_" or "abtt_xp_testx20_" and a successful extraction would look like "testx1" and testx20 respectively.

I have tried both using StringSplit with "_" as spliter, and alternatively also used StringTake but since I don't know whether it's a 1 digit or 2 digit number that follows "testx" I don't lnow how to enforce the extraction. For instance, if test = "abcd_xt_testx1_" then StringTake[test, StringPosition[test,"testx"][[1]]] would yield only "testx" without the number after it (here 1).

  • How can I correctly extract such substrings without a priori knowing how many digits the number that is attached to "testx" contains?
  • $\begingroup$ @march oh surprisingly complicated and neat! Thanks. Would you kindly simply copy paste it as an answer so I can accept? $\endgroup$ – user929304 Apr 18 '19 at 15:26
StringCases[stringExpression, "testx" ~~ Longest[DigitCharacter ..]]

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.