In Javascript, from a string like this, I am trying to extract only the number with a hyphen. ie 67-64-1 and 35554-44-04. Sometimes there could be more hyphens.
The solvent 67-64-1 is not compatible with 35554-44-04
I tried different regex but not able to get it correctly. For example, this regex gets only the first value.
var msg = 'The solvent 67-64-1 is not compatible with 35554-44-04'; //var regex = /\\d+\\-?/; var regex = /(?:\\d*-\\d*-\\d*)/; var res = msg.match(regex); console.log(res);
You just need to add the g
(global) flag to your regex to match more than once in the string. Note that you should use \\d+
, not \\d*
, so that you don't match something like '3--4'. To allow for processing numbers with more hyphens, we use a repeating -\\d+
group after the first \\d+
:
var msg = 'The solvent 67-64-1 is not compatible with 23-35554-44-04 but is compatible with 1-23'; var regex = /\\d+(?:-\\d+)+/g; var res = msg.match(regex); console.log(res);
It gives only first because regex work for first element to test
// g give globel access to find all
var regex = /(?:\d*-\d*-\d*)/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.