简体   繁体   English

正则表达式Javascript,用于匹配第一个特定字符之前的字母数字字符串中的5个非连续数字

[英]Regex Javascript for matching 5 non-consecutive numbers from an alphanumeric string before the first specific character

I am trying to create a regular expression in javascript that matches the last 5 non-consecutive numbers in an alphanumeric string before the first "-" like so... 我正在尝试在JavaScript中创建一个正则表达式,使其与第一个“-”之前的字母数字字符串中的最后5个非连续数字匹配,如下所示...

Take these two strings for example: 以以下两个字符串为例:

7356CH18PRZ2506-01
45D18A234-02-01

For each example above, the match would be: 对于上面的每个示例,匹配项将是:

82506
18234

We are using the last 5 numbers to create a unique identifier in our application per the clients request and they have to be numbers. 我们使用后5个数字根据客户的请求在我们的应用程序中创建一个唯一的标识符,并且它们必须是数字。

I have only been able to extract consecutive numbers and since there are not 5 consecutive numbers before the first "-" in each example, all my attempts have been unsuccessful. 我只能提取连续的数字,并且由于在每个示例中第一个“-”之前没有5个连续的数字,因此我的所有尝试均未成功。

I should probably also mention that I am not the greatest with regular expressions. 我可能还应该提到,我不是最擅长使用正则表达式的人。 I dabble. 我涉足。

If anyone can point me in the right direction, I would appreciate it. 如果有人能指出正确的方向,我将不胜感激。

Also, I would be happy to elaborate on my issue if needed. 另外,如果需要,我很乐意阐述我的问题。

You may use this approach of match + replace 您可以使用match + replace这种方式

 let arr = ['7356CH18PRZ2506-01', '45D18A234-02-01', '012-45D18A234-02-01', 'foobar']; let re = /^[^-]*((?:\\d[^\\d-]*){5})-/; for (i=0; i<arr.length; i++) { let m = arr[i].match(re); if (m) { console.log(arr[i], "=>", m[1].replace(/\\D+/g, '')); } } 

Here: 这里:

  • Within match we use regex /^[^-]*((?:\\d[^\\d-]*){5})-/ to match first 5 digits that may have 0 or more non-digits between them followed by very first hyphen in input match我们使用正则表达式/^[^-]*((?:\\d[^\\d-]*){5})-/来匹配前5位数字,它们之间可能有0或多个非数字输入中的第一个连字符
  • With replace we just remove all non-digits with empty string. 使用replace我们只删除所有带有空字符串的非数字。

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

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