如何使用Regex获取字符串中的字母数字或数字值?

时间:2017-05-30 05:19:58

标签: javascript regex

我想在字符串中获取一个项目

主要字符串是:ABX16059636/903213712,

我想提取Regex有没有办法使用{{1}}来实现这个?

请与我们分享一些建议。

4 个答案:

答案 0 :(得分:2)

尝试使用以下正则表达式,



var string = "This is an inactive AAA product. It will be replaced by replacement AAAA/BBBB number ABX16059636/903213712 during quoting"

var result = string.match(/[A-Z]+[0-9]+\/[0-9]+/g)

console.log(result)




答案 1 :(得分:1)

var s = 'This is an inactive AAA product. It will be replaced by replacement AAAA/BBBB number ABX16059636/903213712 during quoting'
var pat = /[A-Z]{3}\d+\/\d+/i
pat.exec(s)

此正则表达式匹配任意3个字母,后跟一个或多个数字,后跟/,然后是一个或多个数字。

答案 2 :(得分:1)

尝试下面的代码。它会显示您的匹配项以及匹配组。



const regex = /[A-Z]+[0-9]+\/+[0-9]+/g;
const str = `This is an inactive AAA product. It will be replaced by replacement AAAA/BBBB number ABX16059636/903213712 during quoting`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}




Live Demo

答案 3 :(得分:0)

  1. 我去了https://regex101.com/r/ARkGkz/1
  2. 我为你写了一个正则表达式
  3. 我使用他们的代码生成器来生成Javascript代码
  4. 然后,我将Javascript代码修改为仅访问您之后的单个匹配
  5. 结果如下:

    const regex = /number ([^ ]+) /;
    const str = `This is an inactive AAA product. It will be replaced by 
    replacement AAAA/BBBB number ABX16059636/903213712 during quoting`;
    let m;
    
    if ((m = regex.exec(str)) !== null) {
        let match = m[1];
        console.log(`Found match: ${match}`);
    }
    

    正则表达式本身可以理解为:

    1. 第一场比赛number
    2. 括号中包含我们要捕获的部分
    3. [^ ]表示“除空格字符外的任何内容”
    4. +表示“其中一项或多项”
    5. 然后在最后,我们匹配一个尾随空格
    6. 请使用https://regex101.com/r/ARkGkz/1并进行试验。