This code can only retrieve 1.58
, but I also need to match 3.45
. What should I change on my Regexp to do this?
let s = '1.58х3.45';
re = /[0-9/.]+/;
found = s.match(re);
console.log(found);
This code can only retrieve 1.58
, but I also need to match 3.45
. What should I change on my Regexp to do this?
let s = '1.58х3.45';
re = /[0-9/.]+/;
found = s.match(re);
console.log(found);
I'm not exactly sure what you need to find, so let me know if I missed something:
Criteria
.
or a forward slash /
.RegExp
/\d*[./]\d+/g
Segment | Description |
---|---|
/ |
Begin RegExp |
\d* |
Zero or more numbers |
[./] |
Either a literal dot . or a forward slash / |
\d+ |
One or more numbers |
/ |
End RegExp |
g |
Global flag which makes method continue after the first match |
const str = `23.6x1.25 . .2 /2 5.66 .. 5/ 100`;
const rgx = /\d*[./]\d+/g;
const res = str.match(rgx);
console.log(res);
Here is how you can extract two numbers from a string with different delimiters between the numbers:
[
'1.58х3.45',
'1.58&3.45',
'1.58 x 3.45',
'x'
].forEach(str => {
let m = str.match(/([0-9\.]+)[^0-9\.]+([0-9\.]+)/);
console.log(str + ' ==> ' + (m ? 'found: ' + m[1] + ' & ' + m[2] : '(no match)'));
});
1.58х3.45 ==> found: 1.58 & 3.45
1.58&3.45 ==> found: 1.58 & 3.45
1.58 x 3.45 ==> found: 1.58 & 3.45
x ==> (no match)
Explanation:
([0-9\.]+)
-- expect a number (1+ digits or dots), and capture it[^0-9\.]+
-- expect non-number characters([0-9\.]+)
-- expect a number (1+ digits or dots), and capture it