将正则表达式扩展为负数 [英] Extend a regular expression to negative number

查看:104
本文介绍了将正则表达式扩展为负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下正则表达式扩展为负数.

I want to extend the following regex to negative numbers.

this.value = this.value.replace(/[^0-9\.]/g, "");

我尝试添加减号(/[^-0-9.]/g,"),但这允许在数字的任何位置输入减号.我只允许数字开头出现一个减号.以后发生的负号应忽略.

I tried adding minus sign doing something like this, (/[^-0-9.]/g, "") but this allows minus sign to be entered anywhere in the number. I want to allow only one occurance of the minus sign at the beginning of the number. Later occurances of minus should be ignored.

请帮助.

推荐答案

嗯,替换每个非数字字符会使操作更加困难-就像否定"正则表达式一样.我想出的是一个负向超前,可以防止出现负号-这可以通过匹配[^0-9.]-如果beeing在字符串的开头,则匹配它(使用启动锚点):

Uh, replacing every non-number character makes that a bit harder - it's like "negating" the regex. What I came up with is a negative lookahead, preventing a minus - which would be matched by [^0-9.] - from beeing matched if it is in the beginning of the string (using a start anchor):

….replace(/(?!^-)[^0-9.]/g, "")

这篇关于将正则表达式扩展为负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆