Reputation: 6277
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.
Upvotes: 2
Views: 3326
Reputation: 326
Try this regex string, I could run it in regex101 for your case.
/(.+)\s\((.+)\)/g
Upvotes: 0
Reputation: 67968
(.*)\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.
}
Upvotes: 0
Reputation: 7948
use this pattern
(.*\S)\s*\(([^()]+)
( # 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)
Upvotes: 4
Reputation: 388316
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 ()
Upvotes: 0