匹配正则表达式:[编号前的所有内容],[编号]

时间:2014-11-25 02:23:34

标签: javascript jquery regex match

我在一堆变化很大的字符串上使用.match()。我想从字符串中获取括号内的最后一个数字,然后从那里得到所有内容。例如:

1 serving  (57.0 g)
1 slice, small (2" x 2-1/2" x 1-3/4")  (32.0 g)

成为一个阵列:

['1 serving', '57.0 g']
['1 slice, small (2" x 2-1/2" x 1-3/4")', '32.0 g']

各种字符串的列表:http://regex101.com/r/jJ5sF3/1

我一直在努力写一个捕获这个的正则表达式。

4 个答案:

答案 0 :(得分:3)

使用此模式

(.*\S)\s*\(([^()]+)  

Demo

(               # Capturing Group (1)
  .             # Any character except line break
  *             # (zero or more)(greedy)
  \S            # <not a whitespace character>
)               # End of Capturing Group (1)
\s              # <whitespace character>
*               # (zero or more)(greedy)
\(              # "("
(               # Capturing Group (2)
  [^()]         # Character not in [^()]
  +             # (one or more)(greedy)
)               # End of Capturing Group (2)

答案 1 :(得分:0)

试试像

这样的正则表达式
/(.*?)\s*\(([.\d\sg]*?)\)\s*$/gmi
  • (.*?) - 对最后()
  • 之前的所有字符进行分组
  • \s*\( - 将文本内容和(
  • 之后的空格分开
  • ([.\d\sg]*?)对最后()
  • 内的内容进行分组

答案 2 :(得分:0)

(.*)\s(\([^)]*\))

试试这个。看看演示。

http://regex101.com/r/jJ5sF3/3

var re = /(.*)\s(\([^)]*\))/g;
var str = '71 oz (28.4 g)\n1 slice, small (2" x 2-1/2" x 1-3/4") (32.0 g)\n1 slice, small (29.0 g)\n81 oz (28.4 g)\n1 pita, large (6-1/2" dia) (64.0 g)\n21 cup, crumbs (45.0 g)\n61 oz (28.4 g)\n1 cup (108.0 g)\n61 oz (28.4 g)\n1 cup, crumbs (45.0 g)\n41 oz (28.4 g)\n1 serving (57.0 g)\n1 100 g (100.0 g)\n71 oz (28.4 g)\n1 slice, small (2" x 2-1/2" x 1-3/4") (32.0 g)\n1 slice, small (29.0 g)\n81 oz (28.4 g)\n1 pita, large (6-1/2" dia) (64.0 g)\n181 oz (28.4 g)\n21 cup, crumbs (45.0 g)\n61 oz (28.4 g)\n1 cup (108.0 g)\n131 oz (28.4 g)\n1 cup, crumbs (45.0 g)\n1 serving (50.0 g)\n1 100 g (100.0 g) \n1 slice, small (2" x 2-1/2" x 1-3/4") (32.0 g) \n1 slice, small (29.0 g) \n1 pita, large (6-1/2" dia) (60.0 g) \n21 cup, crumbs (45.0 g) \n1 cup (108.0 g) \n131 oz (28.4 g) \n61 oz (28.4 g) \n1 cup, crumbs (45.0 g) \n41 oz (28.4 g) \n1 serving (50.0 g) \n1 100 g (100.0 g';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

答案 3 :(得分:0)

试试这个正则表达式字符串,我可以在你的情况下在regex101中运行它。

/(.+)\s\((.+)\)/g