简体   繁体   English

Javascript正则表达式只允许数字和浮点数

[英]Javascript regex allow only number and float

I have below code for replace anything apart from number/ float from a string.我有以下代码用于替换字符串中除数字/浮点数之外的任何内容。

const parseNumbers = strInput => strInput
  .trim()
  .replace(/^[@#$%^&*()_+}{|{}[\]/<>,.;'"`~a-z!]*/gi, '')
  .replace(/[^0-9]+[.][0-9]*/g, "");

The following strings are not working with the above regex:以下字符串不适用于上述正则表达式:

'644322.abc' '644322.abc'

While this works '644322.abc.....' gets converted to 644322虽然这有效'644322.abc .....'被转换为644322

'644322.12ac.....' gets converts to 644322.12 '644322.12ac .....'被转换为644322.12

But this does not:但这不会:

'644322.12ac' gets converted to 644322.12ac '644322.12ac'被转换为644322.12ac

'644322.12-1' remains as is 644322.12-1 '644322.12-1'保持原样644322.12-1

I want to replace all characters which are not numbers and keep values as number or float.我想替换所有不是数字的字符并将值保留为数字或浮点数。

Can you give an example string?你能举个例子吗? Here is one made up from your question.这是根据你的问题提出的。

 let input = "I have below code for replace anything apart from number/ float from a string.The following strings are not working with the above regex:'644322.abc'While this works '644322.abc.....' gets converted to 644322'644322.12ac.....' gets converts to 644322.12But this does not:'644322.12ac' gets converted to 644322.12ac'644322.12-1' remains as is 644322.12-1" let re = /[+-]?([0-9]*[.])?[0-9]+/g let m = input.match(re); console.log(m)

You can remove all chars other than digits and dots first, and then remove all dots other than the first one (unless that first dot is at the end of the string) and use您可以先删除除数字和点以外的所有字符,然后删除除第一个以外的所有点(除非第一个点位于字符串的末尾)并使用

 const texts = ['644322.abc', '644322.12ac.....', '644322.12ac', '644322.12-1']; texts.forEach( text => console.log( text, '=>', text.replace(/[^\\d.]+/g, '').replace(/^([^.]*\\.)(?!$)|\\./g, '$1') ))

Details :详情

  • .replace(/[^\\d.]+/g, '') - removes all chars other than digits and dots .replace(/[^\\d.]+/g, '') - 删除除数字和点以外的所有字符
  • .replace(/^([^.]*\\.)(?!$)|\\./g, '$1') - removes all dots other than the first one that is not at the end of string. .replace(/^([^.]*\\.)(?!$)|\\./g, '$1') - 删除除第一个不在字符串末尾的点以外的所有点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM