字母数字词的正则表达式

时间:2019-05-30 11:24:13

标签: javascript regex

我需要从字符串中查找并返回模式的首次出现。

示例:您好,我的SNO是05FK3NEK900058V,请添加

预期输出:05FK3NEK900058V

要匹配的模式的条件

  1. 数字和字母的组合
  2. 字符长度在12到16之间

我可以使用正则表达式来执行此操作吗?还是需要循环查看这些单词?

我尝试过但没用的

const regex = /\b^(?!\d*$|[a-zA-Z]*$)[a-zA-Z\d]{12,16}$\b/gm;
const str = `hello my SNO is 05FK3NEK900058V please add it `;
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}`);
    });
}

3 个答案:

答案 0 :(得分:2)

您可以使用单个正则表达式,例如

/\b(?=[a-zA-Z\d]{12,16}\b)(?:[a-zA-Z]*\d|\d*[a-zA-Z])[a-zA-Z\d]*\b/

请参见regex demo

详细信息

  • \b-单词边界
  • (?=[a-zA-Z\d]{12,16}\b)-直到下一个单词边界,必须有12到16个字母数字字符
  • (?:[a-zA-Z]*\d|\d*[a-zA-Z])-0+个字母和一个数字或0+个数字和一个字母
  • [a-zA-Z\d]*-0+个字母数字字符
  • \b-单词边界。

请参见下面的JS演示

var str = "hello my SNO is 05FK3NEK900058V please add it ";
var reg = /\b(?=[a-zA-Z\d]{12,16}\b)(?:[a-zA-Z]*\d|\d*[a-zA-Z])[a-zA-Z\d]*\b/;
var m = str.match(reg) || [""];
console.log(m[0]);

答案 1 :(得分:2)

我认为这会起作用:

[\w\d]{12,16}

Demo

如果您需要匹配一个单词,也可以使用单词边界。

\b[\w\d]{12,16}\b

Demo:

在@PeterM评论后更新:

最新版本更详细但更准确:

string=`Johannsonoff 111111111111111 05FK3NEK900058Vf 05FK3NEK900058Vfaf48 hello my SNO is fFK3NEK9000515 05FK3NEK9000515 please add it 05FK3NEK900058Vfaf48 faf fasf1654 EK90058Vs11 EK9005f8Vs12 05FK3NE90058Vs16 05FK3NEK90058Vs17`;
// Returns an Array in which elements are strings between 12 and 16 characters.
const groupMathed = string.match(/\b[\w\d]{12,16}\b/g)
// Returns the first element that have a digit [0-9] follow by a alphabetic character or a alphabetic character followed by a digit.
const alphanumericWord = groupMathed.find(e => /[0-9]+[a-zA-z]+|[a-zA-z]+[0-9]+/.test(e))
console.log(alphanumericWord)

答案 2 :(得分:0)

let str = "hello (plus SomeLongWord) my SNO is 05FK3NEK900058V please add it ";
const reg = /\b[\w\d]{12,16}\b/g;

let m = str.match(reg);
if (typeof m === "object" && m.length) {
  for (var indexM = 0; indexM < m.length; indexM++) {
    // You can add more checks to filter long words
    console.log(m[indexM]);
  }
} else {
  console.log("Not found any SNO here");
}

// results:
// SomeLongWord
// 05FK3NEK900058V

这将帮助您处理长单词,但可能需要更多检查。