正则表达式,用于匹配不以字母数字开头的字符串

时间:2019-05-21 22:18:01

标签: javascript regex regex-negation regex-group regex-greedy

我正在寻找只接受数字和字母并且第一个字符不能以数字开头的正则表达式。

我发现这样做可以解决所有时间都无法解决的问题:

export const cannotBeginWithAdigit= new RegExp("/^d/");
export const canOnlyContainNumsbersAndDigits = new RegExp('/[,"/\\[]:|<>+=.;?*]/g');

我将正则表达式放在||之间测试第一个然后测试第二个。

其他无效的方法:

^d{1}[0-9a-zA-Z]

2 个答案:

答案 0 :(得分:1)

在这里,我们可以用一个不以数字开头的数字(^开头([^\d]),然后是所需的字符列表:

^[^\d][A-Za-z0-9]+

DEMO

然后,我们还可以添加其他边界。例如,通过添加结束字符并使用i标志,可以使anubhava在注释中的建议很好:

/^[a-z][a-z\d]*$/i

测试

const regex = /^[^\d][A-Za-z0-9]+/gm;
const str = `123abc
abc123abc
`;
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}`);
    });
}

RegEx电路

jex.im可视化正则表达式。

enter image description here

enter image description here

答案 1 :(得分:-1)

尝试/^\D{1}\w+$/

说明:

\D表示仅选择非数字,{1}将匹配限制为单个字母。 \w是单词匹配,它匹配所有字母数字,但不匹配其他任何字符。 +,以确保\w中有多个字母。您可以对其进行修改以满足自己的要求。