如何排除以货币符号开头的数字

时间:2018-03-04 23:05:22

标签: javascript regex

我想忽略代表文本中任何地方价格的数字。

它应匹配

3.5 mm
-2
#1

应该忽略

$3.50

到目前为止,我有一个Javascript的正则表达式

([^\$¢£]([0-9]+(\.[0-9]+)?))([^a-zA-Z]|$)

但这仍然会与3.50相提并论,只是将美元符号排除在外。 缺少什么来忽略整数?

编辑: 用于测试https://regex101.com/r/9SLNo2/1

5 个答案:

答案 0 :(得分:1)

您需要通过在前面添加^来将匹配锚定到字符串的开头。我不太明白你的正则表达式中你想要完成的是什么。

如果您只想要任何不以货币符号开头的内容,请尝试^[^\$¢£].*$。 任何不包含任何货币符号的内容,请尝试^[^\$¢£]*$。 包含数字的任何内容(可选的十进制,总是包含您似乎想要的整个部分),可选地包含"非货币符号",尝试^[^\$¢£]*[0-9]+(\.[0-9]+)?[^\$¢£]*$

答案 1 :(得分:1)

不幸的是,JS不支持lookbehinds,但你可以使用"技巧":
匹配不想捕获 想要的任何内容:

junk_a|junk_b|junk_c|(interesting_stuff)

所以这里有你的具体例子:

[$¢£]\s*-?\d+(?:\.\d+)?|(-?\d+(?:\.\d+)*)
# ^^^^^ junk part ^^^^^

<小时/> 然后,使用一个比较来检查是否设置了组1(interesting_stuff):

&#13;
&#13;
let data = 'lorem ipsum 3.5 mm -2 #1 lorem ipsum $3.50 lorem ipsum';
let regex = /[\$¢£]\s*\d+(?:\.\d+)*|(-?\d+(?:\.\d+)*)/g;
let interesting = [];

while ((match = regex.exec(data)) !== null) {
    if (typeof(match[1]) != "undefined") {
        interesting.push(match[1]);
    }
}

console.log(interesting);
&#13;
&#13;
&#13;

请参阅a demo on regex101.com(需要针对单位进行调整)。

答案 2 :(得分:0)

您可以忽略以美元符号开头的值...

&#13;
&#13;
var values = ['3.5 mm', '-2', '#1', '$3.50'];

var regex = new RegExp('^\\$');
var res = values.filter(function(val) {
  if (val.match(regex)) {
    console.log(val, 'skip');
  } else {
  return val;
  }
})

console.log(res);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

&#13;
&#13;
function check() { // if you want to match only numbers at the bigining as well as #
  var a = document.getElementById("test").value;
  var remove = /^-?\d*\.?\d+|#/;
  var b = a.match(remove);
  if (!b)
    console.log("ignore");
  else
    console.log("true");
}

function check2() { // if you want to ignore first charcter if match these $,¢ and £ and allow others
  var a = document.getElementById("test").value;
  var remove = ['$', '¢', '£'];
  var b = a.charAt(0);
  if (remove.indexOf(b) != -1)
    console.log("ignore");
  else
    console.log("true");
}
&#13;
<input type="text" onblur="check();check2()" id="test">
&#13;
&#13;
&#13;

答案 4 :(得分:0)

作为替代方案,也许您可​​以匹配代表价格的数字并将匹配替换为空字符串:

[£$¢]\d+(?:\.\d+)? *

&#13;
&#13;
var pattern = /[£$¢]\d+(?:\.\d+)? */g;
var text = `3.5 mm
This is 3.5 mm.
-2
This is -2 and test
This is #1 and test
#1
$3.50
$3.50
This is $3.50.
This is $3.50 a test
This is a £100000 test and $5000.00 test.
This is a ¢100000 test`;

console.log(text.replace(pattern, ""));
&#13;
&#13;
&#13;