仅打印两个符号之间的文本

仅打印两个符号之间的文本

我有一个包含一些文本的宏:

\textmacro{This is some text.}

正常情况下,编译时应该只打印文本,如下所示:

This is some text.

有时,文本中也会包含“①”和“②”,比如:

\textmacro{①  This is some text. ② This is some other text.}

当发生这种情况时,我需要它仅打印出现在“①”和“②”之间的文本,如下所示:

This is some text.

如果出现“①”和“②”符号,如何让宏打印出它们之间的文本#1,否则只打印所有文本?

答案1

你想要一个 ConTeXt 答案,对吧?每当我发现自己想“我知道如何用普通的编程语言做到这一点”时,我就会将我想要操作的文本转移到 LuaTeX 中。来自 wiki 的模板

% First, the Lua function that will process the string
\startluacode
    -- remember, using the userdata namespace prevents conflicts
    userdata = userdata or {}

    function userdata.printBetweenMarks(str, m1, m2)
        -- default delimiters
        m1 = m1 or '①'
        m2 = m2 or '②'

        match_pattern = string.format('%s(.*)%s', m1, m2)
        str = string.match(str, match_pattern) or str
        context(str)
    end
\stopluacode

% Secondly, the ConTeXt command that passes the string to the Lua function.

\def\textmacro#1%
    {\ctxlua{userdata.printBetweenMarks([===[#1]===])}}
    % Note that Lua sees the text as-is, so we have to wrap it in string
    % delimiters ourselves.
    % [=*[ is Lua's double-bracket string delimiter style; this way, the
    % code only fails if the text contains ']===]'.

编辑:删除了print()我用于调试的语句

答案2

\documentclass{article}
\makeatletter
\def\textmacro#1{\expandafter\@textmacro#1①②\@nil}
\def\@textmacro#1①#2②#3\@nil{%
  \ifx\relax#2\relax#1\else#2\fi}
\makeatother
\begin{document}
\textmacro{This is some text.}\par
\textmacro{①  This is some text. ② This is some other text.}\par
\textmacro{This is some text ①  This is some other text. ② This is some text.}
\end{document}

在此处输入图片描述

相关内容