简体   繁体   English

如何过滤除与Javascript中特定模式匹配的非数字字符之外的非数字字符?

[英]How to filter out non-numeric characters except ones matching a specific pattern in Javascript?

I have an array containing strings that represent numbers.我有一个包含表示数字的字符串的数组。 The only two valid types of elements in the array are:数组中仅有的两种有效元素类型是:

  1. All-numeric strings (Eg: "123","123344")全数字字符串(例如:“123”、“123344”)
  2. Strings that match a specific pattern of xxx-xxxxx where all x are numbers (Eg:"123-12345", "233-30000").匹配特定模式 xxx-xxxxx 的字符串,其中所有 x 都是数字(例如:“123-12345”、“233-30000”)。

This pattern can be added to more values in the future ie xx-xxxxx and x-xx-xxx where all x are still numbers:将来可以将此模式添加到更多值,即 xx-xxxxx 和 x-xx-xxx,其中所有 x 仍然是数字:

I have the below code which solves 1 but not 2 :我有以下代码可以解决 1 但不能解决 2 :

const arr = ["ab's-test#s", "ab-c", "124", "123-12345"];
var arr2 = arr.filter(function(el) {
    return el.length && el==+el && el.match(new RegExp("^\\d{3}(-\\d{5})?$"));
});
console.log(arr2)

This prints out ["124"] However - I want it to print out ["124","123-12345"]这会打印出["124"]但是 - 我希望它打印出["124","123-12345"]

Is there a way I can allow numbers and numeric patterns as a part of the same filter function?有没有办法允许数字和数字模式作为同一个过滤器功能的一部分? Thanks in advance.提前致谢。

You can use conditional OR with regex to test your string is either number or number with pattern xxx-xxxxx .您可以使用带有正则表达式的条件 OR 来测试您的字符串是数字还是具有模式xxx-xxxxx

 const arr = ["ab's-test#s", "ab-c", "124", "123-12345"], arr2 = arr.filter((str) => /^\\d{3}-\\d{5}$/.test(str) || /^\\d+$/.test(str)); console.log(arr2)

You can use a single pattern placing the or |您可以使用单个模式放置或| in the regex itself, using a non capture group (?:....) to match either of the alternatives between the anchors to assert the start and the end of the string:在正则表达式本身中,使用非捕获组(?:....)来匹配锚点之间的任一选项以断言字符串的开头和结尾:

The updated pattern will become:更新后的模式将变为:

^(?:\d{3}-\d{5}|\d+)$

 const arr = ["ab's-test#s", "ab-c", "124", "123-12345"]; const arr2 = arr.filter(str => /^(?:\\d{3}-\\d{5}|\\d+)$/.test(str)); console.log(arr2)

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

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