Im beginer about regex...I need to create a regular expression to check if a string has got at least one special character and one numeric. Im using ([0-9]+[!@#$%\^&*(){}[\]<>?/|\-.:;_-]+|[!@#$%\^&*(){}[\]<>?/|\-.:;_-]+[0-9]+)
, but is not working. Help please.

- 25
- 4
- 8
-
can u post your code which is not working....a jsfiddle would be good.. – iJade Sep 19 '13 at 10:58
-
1In what way is it not working? Errors? Not doing what you think it should? Actual output vs expected output would be helpful – MDEV Sep 19 '13 at 10:58
-
Check this link http://stackoverflow.com/questions/7102582/regular-expression-check-for-special-character-or-number – Nitish Sep 19 '13 at 10:59
-
No matter the order, for example: aA*8 or 8p: – j_arab Sep 19 '13 at 11:06
3 Answers
One simple way to check is to do 2 tests on the input string for the existence of each type of character:
/[0-9]/.test(inputString) && /[special_characters]/.test(inputString)
The code will do as you described: check if there is at least 1 digit, and at least 1 special character in the inputString
. There is no limit on the rest of the inputString
, though.
Fill in special_characters
with your list of special characters. In your case, it would be:
/[0-9]/.test(inputString) && /[!@#$%^&*(){}[\]<>?/|.:;_-]/.test(inputString)
I removed a few redundant escapes in your pattern for special character. (^
doesn't need escaping, and -
is already there at the end).
This make the code readable and less maintenance headache, compared to trying to write a single regex that do the same work.

- 55,989
- 15
- 126
- 162
try this regex expression
(.*[0-9]+[!@#$%\^&*(){}[\]<>?/|\-]+|.*[!@#$%\^&*(){}[\]<>?/|\-]+[0-9]+)

- 23,144
- 56
- 154
- 243
If, by special characters, you mean all ASCII printable symbols and punctuation that can be matched with [!-\/:-@[-`{-~]
pattern (see Check for special characters in string, you may find more special character patterns there), you may use
/^(?=.*?\d)(?=.*?[!-\/:-@[-`{-~])/
Or, taking into account the contrast principle:
/^(?=\D*\d)(?=[^!-\/:-@[-`{-~]*[!-\/:-@[-`{-~])/
See the regex demo (I added .*
at the end and \n
to the negated character classes in the demo because the regex is tested against a single multiline string there, you do not need them in the regex testing method in the code).
Details
^
- start of string(?=.*?\d)
- there must be at least one digit after any 0 or more characters other than line break chars, as few as possible(?=\D*\d)
- there must be at least one digit after any 0 or more characters other than a digit(?=.*?[!-\/:-@[-
{-~])` - there must be at least one printable ASCII punctuation/symbol after any 0 or more characters other than line break chars, as few as possible(?=[^!-\/:-@[-
{-~]*[!-/:-@[-{-~])
- there must be at least one printable ASCII punctuation/symbol after any 0 or more characters other than a printable ASCII punctuation/symbol.

- 607,720
- 39
- 448
- 563