3

I want to check by regex if:

  1. String contains number
  2. String does not contain special characters (!<>?=+@{}_$%)

Now it looks like: ^[^!<>?=+@{}_$%]+$

How should I edit this regex to check if there is number anywhere in the string (it must contain it)?

tehteh
  • 39
  • 1
  • 3
  • What is everything that the regex should allow? This is how I would go about it to make it much simpler. – 10100111001 Jul 20 '16 at 02:21
  • Using an online regex checker might help. See this tool https://regex101.com/ – JiminyCricket Jul 20 '16 at 02:24
  • Regex should allow all the strings that does not contain special characters AND contain at least one number. It will be used to check if there is a number in address field. – tehteh Jul 20 '16 at 02:26

3 Answers3

3

you can add [0-9]+ or \d+ into your regex, like this:

^[^!<>?=+@{}_$%]*[0-9]+[^!<>?=+@{}_$%]*$ or ^[^!<>?=+@{}_$%]*\d+[^!<>?=+@{}_$%]*$

different between [0-9] and \d see here

Community
  • 1
  • 1
蒋宜通
  • 56
  • 1
  • 1
    It's quite unsatisfying to have the same character class repeated twice in the same regexp. By the way, the link you posted is for Python. In JS, `\d` is **exactly** equivalent to `[0-9]`. –  Jul 20 '16 at 04:41
  • @torazaburo Perhaps in JS this is the case, but I seem to recall that `\d` can include unicode characters in some other flavor of regex. – Tim Biegeleisen Jul 20 '16 at 05:02
  • Sure, but this question is about JS. –  Jul 20 '16 at 05:25
2

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.

0

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.

Whothehellisthat
  • 2,072
  • 1
  • 14
  • 14