Home > Mobile >  javascript regex [-_.] not first character
javascript regex [-_.] not first character

Time:12-13

I do not want the first letter of these characters _-. Used but can use between characters

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

CodePudding user response:

If [a-zA-Z0-9-. ] is the allowed range of characters, should be present 1-10 times and can not start with - or . then you don't need lookarounds.

You can match the first character [a-zA-Z0-9 ] and repeat the fully allowed range 0-9 times.

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

See a regex demo.

If an underscore is also allowed, you could shorten the pattern using \w:

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

CodePudding user response:

I tweaked with some tools online and the follwoing do should do the job fine:

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}`);
    });
}

I also recommend using the website regex101.com if you wanted to play around with the Javscript regex.

  • Related