Regex grep与有效括号序列
我需要从我的latex文件中提取所有索引。但有些指数可能是这样的 \索引{*3*sqrt*uppersqrt{\hspace{-2.5pt}$\uppersqrt{\;\;\;}$(上) 平方根)}} 所以我需要在正则表达式中计算当前打开的花括号的数量。我不知道如何处理这样的案件 另外,如果索引包含Regex grep与有效括号序列,regex,grep,Regex,Grep,我需要从我的latex文件中提取所有索引。但有些指数可能是这样的 \索引{*3*sqrt*uppersqrt{\hspace{-2.5pt}$\uppersqrt{\;\;\;}$(上) 平方根)}} 所以我需要在正则表达式中计算当前打开的花括号的数量。我不知道如何处理这样的案件 另外,如果索引包含/,那么我不需要这样的索引 例如: Anything before. \index{{}{}}\index{Hi}\anothertag{something} \index{}{} \index{/}
/
,那么我不需要这样的索引
例如:
Anything before. \index{{}{}}\index{Hi}\anothertag{something}
\index{}{}
\index{/}
预期结果是
\index{{}{}}
\index{Hi}
\index{}
可以打开的支架数量有限? 正则表达式
\\index{(?:[^{]|(?:{(?:[^{]|(?:{[^{]*}))*}))*}
将匹配最多3个深括号,如:\index{{{{}{{{}}可以打开的括号数量有限吗? 正则表达式
\\index{(?:[^{]|(?:{(?:[^{]|(?:{[^{]*}))*}))*}
将最多匹配3个括号深,如:\index{{{}{{}}{{{}}Regex:
\\index({(?(?!{|})[^\/{}]*|(?1))*})
说明:
\\index # Match `\index` literally
( # Start of capturing group (1)
{ # Match opening brace `{`
(? # Start of conditional statement
(?!{|}) # If very next immediate character is not `{` or `}`
[^\/{}]* # Anything except these characters
| # Else
(?1) # Recurs capturing group (1)
)* # End of conditional - repeat conditional zero or more times - greedily.
} # Match closing brace `}`
) # End of capturing group (1)
用法:
grep -Po "\\index({(?(?!{|})[^\/{}]*|(?1))*})" input_file.txt
基于OP提供的输入的输出:
\index{{}{}}
\index{Hi}
\index{}
正则表达式:
说明:
\\index # Match `\index` literally
( # Start of capturing group (1)
{ # Match opening brace `{`
(? # Start of conditional statement
(?!{|}) # If very next immediate character is not `{` or `}`
[^\/{}]* # Anything except these characters
| # Else
(?1) # Recurs capturing group (1)
)* # End of conditional - repeat conditional zero or more times - greedily.
} # Match closing brace `}`
) # End of capturing group (1)
用法:
grep -Po "\\index({(?(?!{|})[^\/{}]*|(?1))*})" input_file.txt
基于OP提供的输入的输出:
\index{{}{}}
\index{Hi}
\index{}
对于第一种情况,贪心点对你不起作用吗
\\index{.*}
@revo我认为它可以将多个索引匹配在一起。您将索引的哪一部分称为索引?@revo整个这样的表达式,但在这样的表达式之后可能有任何文本。这基本上是grep
不适合做的事情:。现在,grep
的查询语言并不完全是规则的,但它很好地近似于何时(不)使用grep
和类似的工具。对于第一种情况,贪婪点不适合你吗\\index{.*}
@revo我认为它可以将多个索引匹配在一起。您将索引的哪一部分称为索引?@revo整个这样的表达式,但在这样的表达式之后可能有任何文本。这基本上是grep
不适合做的事情:。现在,grep
的查询语言不是完全规则的,但它很好地近似于何时(不)使用grep
和类似的工具。这个\index{{{}{{}{{}{{}}{{}}{/code>怎么样?我认为它是一个有效的序列,应该匹配。仅供参考,我投了赞成票,因为你的信息很有用。你这边的问题是什么?这个\index{{{{}{{{{}}{{}}{{}}{{}}{}}{{code>怎么办?我认为这是一个有效的序列,应该匹配。仅供参考,我投了赞成票,因为你的信息很有用。你这边有什么问题?