简体   繁体   中英

Match Regex: [everything before number], [number]

I'm using a .match() on a bunch of strings that vary quite a bit. I'm wanting to get the last number inside a bracket from the string, and from there get everything before that. So for example:

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

Becomes an array of:

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

A list of the various strings: http://regex101.com/r/jJ5sF3/1

I've struggling to write a regex that captures this.

use this pattern

(.*\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)

Try a regex like

/(.*?)\s*\(([.\d\sg]*?)\)\s*$/gmi
  • (.*?) - group all the characters before the last () set
  • \\s*\\( - separate the spaces after the text content and (
  • ([.\\d\\sg]*?) group the contents inside the last ()
(.*)\s(\([^)]*\))

Try this.See demo.

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.
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM