匹配任何字符但数字(负数,小数)

时间:2014-05-12 16:21:43

标签: javascript regex

我需要你的帮助,因为我被困在正则表达式上。

正则表达式需要匹配除第一个数字之外的任何字符。 第一个数字可以是整数,负数,小数。

所以我有RegExp:

var b = /[-]?[0-9]+([\.][0-9]+)?/;

但是当我在JavaScript中这样做时:

var a = 'ab123ab45',
b = /[-]?[0-9]+([\.][0-9]+)?/;

a.replace(b, '');

它显然会回归:abab45

但正如你所理解的那样,我需要的是另一种方式。 以下是一些例子。

123 -> 123
123a -> 123
a123a -> 123
123ab45 -> 123
ab123ab45 -> 123
a1b2c3 -> 1
a1.2b -> 1.2
a1,2b -> 1

我需要使用替换函数只使用1个正则表达式。

3 个答案:

答案 0 :(得分:0)

尝试:

m = a.match(b);
console.log(m[0]);

答案 1 :(得分:0)

如果你需要替换(不匹配):

var a = 'ab123ab45',
b = /.*?([-]?[0-9]+([\.][0-9]+)?).*/;

a.replace(b, '$1');

答案 2 :(得分:0)

试试这个;

var a = "a1b2c3";
a = a.replace(/^.*?([.,\d]+).*?$/, "$1");
alert(a);

LIVE DEMO

正则表达式解释

^.*?([.,\d]+).*?$

Assert position at the beginning of the string «^»
Match any single character that is not a line break character «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the regular expression below and capture its match into backreference number 1 «([.,\d]+)»
   Match a single character present in the list below «[.,\d]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      One of the characters “.,” «.,»
      A single digit 0..9 «\d»
Match any single character that is not a line break character «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»