用于提取[]之间内容的正则表达式



我有一个表达式:

[training_width]:lofmimics

我想提取[]之间的内容,在上面的例子中我想要

training_width

我试过以下几种:

QRegularExpression regex("[(.*?)]");
QRegularExpressionMatch match = regex.match(strProcessed);
QString textYouWant = match.captured(1);

其中strProcessed包含原始文本,但到目前为止它不起作用。

正则表达式的主要问题是反斜杠必须加倍。

因此,有两种解决方案:

  • 使用.*?使反斜杠加倍的模式("\[(.*?)\]"

样品:

QRegularExpression regex("\[(.*?)\]");
QRegularExpressionMatch match = regex.match(strProcessed);
QString textYouWant = match.captured(1);
  • 使用与除[]之外的0+个字符匹配的否定字符类[^\]\[]*

样品:

QRegularExpression regex("\[([^\]\[]*)\]");
QRegularExpressionMatch match = regex.match(strProcessed);
QString textYouWant = match.captured(1);

它们之间的区别在于,由于QRegularExpression实现了类似Perl的regexp,第一个不匹配换行符(由于类似Perl的正则表达式中的.默认情况下不匹配换行,因此需要指定QRegularExpression::DotMatchesEverythingOption标志)。第二个,因为它使用了一个否定的字符类,它将匹配[和下一个最接近的]之间的任何内容,甚至换行符。

只需尝试以下模式:

\[([^\]]*)

所以$1包含了预期的结果。

在线演示

最新更新