最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex - must contain number and must not contain special character - Stack Overflow

programmeradmin1浏览0评论

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)?

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)?

Share edited Jul 20, 2016 at 4:41 user663031 asked Jul 20, 2016 at 2:15 tehtehtehteh 391 silver badge3 bronze badges 3
  • What is everything that the regex should allow? This is how I would go about it to make it much simpler. – 10100111001 Commented Jul 20, 2016 at 2:21
  • Using an online regex checker might help. See this tool regex101. – JiminyCricket Commented Jul 20, 2016 at 2: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 Commented Jul 20, 2016 at 2:26
Add a ment  | 

3 Answers 3

Reset to default 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

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.

发布评论

评论列表(0)

  1. 暂无评论