Home > Enterprise >  How to take numers from string after special sumbol? /[0-9/.] /
How to take numers from string after special sumbol? /[0-9/.] /

Time:10-14

This code can only retrieves 1.58, but I also need to take 3.45. How can I do it? How to rewrite the regex to do this.

The x in the string I can change for special symbol for example &, if it helps.

let s = '1.58х3.45';
re = /[0-9/.] /;
found = s.match(re);
console.log(found);

CodePudding user response:

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)'));
});
Output:

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

CodePudding user response:

I'm not exactly sure what you need to find, so let me know if I missed something:

Criteria

  1. A non-number character either a literal dot . or a forward slash /.
  2. One or more numbers must follow that symbol.
  3. Optionally, one or more numbers may precede that symbol as well.
  4. Multiple matches must be made if there are any.

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);

  • Related