Regex!
The main problem here will be that you've got syntax-based rules in case of the nested expressions, i.e. when you're matching \comandnameE{ ... }
you don't want to match until the first }
, but after the parenthesis balance is even again. I don't know how to take care of that using only Regex. Anyway,
(* Your string condensed into one line *)
tex = "\\commandnameA{Bob}\nblabla\n\n\n\n \\commandnameB{It wasn't Bob}\n\n \\commandnameC{2012}\n\nbla\n\n \\commandnameD{$\\frac{1}{3}$}\n\n \\commandnameE{\\commandnameF{It was Bob!}}\n\n \\commandnamefilename{29}";
(* Regex that matches the inside of a parenthesis of
a `commandname` instruction *)
regex = RegularExpression["\\\\commandname[a-zA-Z]+\{(.+)\}"];
(* Apply regex *)
StringCases[tex, regex -> "$1", Overlaps -> True]
List[
Bob,
It wasn't Bob,
2012,
$\frac{1}{3}$,
\commandnameF{It was Bob!},
It was Bob!},
29
]
Note the trailing }
in the It was Bob!}
line, which you may have to take care of manually.
The regex is replaced by $1
, which is the first matched sub-pattern, i.e. the first parenthesis expression in the regex. $0
would have been the entire expression, i.e. the resulting list would contain all the \commandnameX
, the curly braces and so on.
The Overlaps
parameter lets the regex match single characters multiple times, i.e. after matching commandE
, the already matched character sequence is searched again, yielding the contents of commandF
.
If you want to incorporate a dictionary of possible \commandX
, simply replace the command
in the regex by (command1|foo|bar|command12|...)
.
\commandnameA
etc. to write into some file which you then can read into Mathematica. $\endgroup$commandnameA
etc. to write their content into a special file (in addition to what they normally do). That way you'd even get the information if someone invoked them indirectly, e.g. using\let\cnA=\commandnameA
and then later\cnA{Bob}
. However, if the macros always appear literally, that would be overkill. Anyway, the process of writing to a file from LaTeX is described in stackoverflow.com/q/2115379/1032073 $\endgroup$