-1

i have this regex to get the unit, but i only can get an unit (8.5 lb), i want to get everything (8.5 lb, 25.4 lb)

let data=`<br><span style="font-size: 15px;"><span style="color: #000000;">• 8.5 lb, 25.4 lb</ `

const regex = / \s*([0-9]+(?:\.\d+)?(?:\s*(?:l[ lb ]|lb))?)\b/g;
let m = regex.exec(data)
console.log(m)
  • @Nicolas in this moment i get only (8.5 lb) i wan to get (8.5 lb, 25.4 lb) –  Aug 07 '20 at 15:35
  • Does this answer your question? [RegEx to extract all matches from string using RegExp.exec](https://stackoverflow.com/questions/6323417/regex-to-extract-all-matches-from-string-using-regexp-exec) – Ryszard Czech Aug 07 '20 at 19:25

3 Answers3

0

exec returns just the first match. Call it repeatedly to get all matches. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

Alternatively, use String.prototype.match() instead of exec.

sbolel
  • 3,486
  • 28
  • 45
Doug Domeny
  • 4,410
  • 2
  • 33
  • 49
0

Regular Expression

The following regular expression matches 1 or more groups of (decimal number followed by character words):

/([0-9\.]+\s+\w+)/g
  • [0-9\.]+: matches a sequence consisting of one or more of the following: numbers, the literal "." character
  • \s+ matches any whitespace character (equal to [\r\n\t\f\v ] one or more times
  • \w+ matches any word character (equal to [a-zA-Z0-9_])
  • (...) groups the entire above match
  • g modifier: returns all matches (don't return after first match)

The JavaScript

as @DougDomeny said,

exec returns the first match. Call it repeatedly to get all matches.

You can use String.prototype.match() instead of exec. String.prototype.match() returns:

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

  • If the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.
  • If the g flag is not used, only the first complete match and its related capturing groups are returned. In this case, the returned item will have additional properties as described below.
const regex = /([0-9\.]+\s+\w+)/g;
const m = data.match(regex)
console.log(m)

Result:

> ["8.5 lb", "25.4 lb"]
sbolel
  • 3,486
  • 28
  • 45
-1

You could alter your regex to match the comma as well, and repeat your capture group for one or multiple time.

  \s*(( )?[0-9]+(?:\.\d+)?(?:\s*(?:l[ lb ]|lb))?(, )?)+\b

Here, I've added (, )? and repeated the regex one or multiple time.

I've also added ( )? so your cases can start with a space.

You can test more cases here

Doug Domeny
  • 4,410
  • 2
  • 33
  • 49
Nicolas
  • 8,077
  • 4
  • 21
  • 51
  • i get an array [ " 8.5lb, 25.4 lb", "25.4 lb", undefined, undefined ] –  Aug 07 '20 at 15:51