簡體   English   中英

javascript 正則表達式 [-_.] 不是第一個字符

[英]javascript regex [-_.] not first character

我不想要這些字符的第一個字母_-. 已使用但可以在字符之間使用

'(^[a-zA-Z0-9-_. ]*$){1,10}'

如果[a-zA-Z0-9-. ] [a-zA-Z0-9-. ]是允許的字符范圍,應該出現 1-10 次,不能以-或 開頭. 那么你不需要環顧四周。

您可以匹配第一個字符[a-zA-Z0-9 ]並重復完全允許的范圍 0-9 次。

^[a-zA-Z0-9][a-zA-Z0-9. -]{0,9}$

查看正則表達式演示

如果也允許使用下划線,則可以使用\w縮短模式:

^[a-zA-Z0-9][\w. -]{0,9}$

我在網上使用了一些工具進行了調整,以下操作應該可以很好地完成工作:

const regex = /^[^\_\-\.]{1}(.)*/gm;
const str = `.awdawd`;
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}`);
    });
}

如果您想使用 Javscript 正則表達式,我還建議您使用網站 regex101.com。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM