正则表达式匹配编号不在乳胶数学模式中

时间:2014-09-22 02:18:16

标签: regex latex

我有这样的陈述:

"there is a LaTex is ${ \\frac{123}{456} }$
and a pure number 789 and another LaTex ${ 9^{n+1} }$"`

我需要一个正则表达式来获取数字 789 ,而不是数学模式中的数字。

1 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式:

/(?:^|\}\$)(?:.(?!\$\{))*?(\d+)/

说明:

(?:        # a non-capturing group
  ^|\}\$   # either the beginning of the string, or a "}$"
)          # this will make sure we're not currently in a LaTeX thingy

(?:        # another non-capturing group
  .        # any character
  (?!\$\{) # not followed by a "${" (make sure we don't go into a LaTeX thingy)
)*?        # repeated zero or more times

(\d+)      # the number that you want!

我假设您的LaTeX将是良好的形式;即你不会有${ 123 }$ }$ 456 ${ 789 }$这样的字符串,括号不匹配。

试一试:

var regex = /(?:^|\}\$)(?:.(?!\$\{))*?(\d+)/;
var str = 'there is a LaTex is ${ \\frac{123}{456} }$ and a pure number 789 and another LaTex ${ 9^{n+1} }$';
alert(str.match(regex)[1]);