4
$\begingroup$

This question already has an answer here:

Hi i'm new to programming and it's my first question, so please go easy on me. I want to create a function that extracts text which is between BEGIN and >. For example with a string of text:

str="Random stuff here TEXT BEGIN extract this text > here is other stuff >"

The function should extract the text between BEGIN and >. The text in-between, can be anything from symbols like \n or be another string.

I know I can get every instance of BEGIN with position,

Position[StringSplit[str],"BEGIN"]

but how do I get the position of the next instance of > from BEGIN, so I can extract the text in-between? Or is there a smarter way of doing this?

$\endgroup$

marked as duplicate by Mr.Wizard Jul 1 '17 at 5:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6
$\begingroup$
StringCases[str, "BEGIN" ~~ x : Shortest[___] ~~ ">" :> x]

{" extract this text "}

StringCases["Random stuff here TEXT BEGIN extract \n this text > here is other stuff >", 
 "BEGIN" ~~ x : Shortest[___] ~~ ">" :> x]

{" extract
this text "}

To trim the white space around extracted string use StringTrim on the previous results or on the right hand side of the replacement rule:

StringCases[str, "BEGIN" ~~ x : Shortest[___] ~~ ">" :> StringTrim[x]]

{"extract this text"}

$\endgroup$
1
$\begingroup$
str = "Random stuff here TEXT BEGIN extract this text > here is other stuff >";

StringTake[str, #]&[Last@First@StringPosition[str, #] & /@ {"BEGIN", ">"} + {2, -2}]
$\endgroup$

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