I want to check by regex if:
Now it looks like:
^[^!<>?=+@{}_$%]+$
How should I edit this regex to check if there is number anywhere in the string (it must contain it)?
I want to check by regex if:
Now it looks like:
^[^!<>?=+@{}_$%]+$
How should I edit this regex to check if there is number anywhere in the string (it must contain it)?
you can add [0-9]+
or \d+
into your regex, like this:
^[^!<>?=+@{}_$%]*[0-9]+[^!<>?=+@{}_$%]*$
or
^[^!<>?=+@{}_$%]*\d+[^!<>?=+@{}_$%]*$
different between [0-9]
and \d
see here
Just look ahead for the digit:
var re = /^(?=.*\d)[^!<>?=+@{}_$%]+$/;
console.log(re.test('bob'));
console.log(re.test('bob1'));
console.log(re.test('bob#'))
The (?=.*\d)
part is the lookahead for a single digit somewhere in the input.
You only needed to add the number check, is that right? You can do it like so:
/^(?=.*\d)[^!<>?=+@{}_$%]+$/
We do a lookahead (like peeking at the following characters without moving where we are in the string) to check to see if there is at least one number anywhere in the string. Then we do our normal check to see if none of the characters are those symbols, moving through the string as we go.
Just as a note: If you want to match newlines (a.k.a. line breaks), then you can change the dot .
into [\W\w]
. This matches any character whatsoever. You can do this in a number of ways, but they're all pretty much as clunky as each other, so it's up to you.