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

问题描述 投票:1回答:5

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

它应该匹配

3.5 mm
-2
#1

它应该忽略

$3.50

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

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

但这仍然会与3.50排除美元符号。缺少什么来忽略整数?

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

javascript regex
5个回答
1
投票

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

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


1
投票

不幸的是,JSbut不支持lookbehinds你可以使用“技巧”: 匹配任何你不想要的东西,但捕捉你想要的任何东西:

junk_a|junk_b|junk_c|(interesting_stuff)

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

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


Afterwards, use a little comparison that checks if the group 1 (the interesting_stuff) is set:

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

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


0
投票

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

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

0
投票

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");
}
<input type="text" onblur="check();check2()" id="test">

0
投票

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

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

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, ""));
© www.soinside.com 2019 - 2024. All rights reserved.