Regex:

^(?=[a-zA-Z0-9#@)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*

Explanation:

In the regex you provided, the lookaheads serves to ensure your string met some specific conditions, but they are not the real filter which keeps out undesired strings. You specified the following conditions:

  • (?=.*?[A-Z]): Match at least one uppercase letter.
  • (?=.*?[a-z]): Match at least one lowercase letter.
  • (?=.*?[0-9]): Match at least one number.
  • (?=.*?[#@$?]): Match at least one of these characters: #@$?
  • .{8,}: Match any character at least 8 times.

But there are at least two flaws:

  • The (?=.*?[#@$?]) part is unnecessary because those special characters are meant to be optional, not mandatory[1].

  • As I said before, you did not specify a real filter, so thanks to the .{8,} part, your regex will accept any string as long as it meets the conditions established by the lookaheads, even if it has undesired special characters[1].

So to solve those flaws it is necessary to:

  • Delete the (?=.*?[#@$?]) part.

  • Add a new lookahead that acts as the filter mentioned above.

To construct this filter, you should think "which characters I want to allow?" instead of "which characters I want to disallow?", because that is a easier scenario to handle in this specific case. If you say you only want a-z, A-Z, 0-9 and #@$? to be your allowed characters, then the lookahead should look like this:

(?=[a-zA-Z0-9#@$?])

But hey, in this step you can even set the minimum length and tell the lookahead where to start and where to stop (the start and end of string in this case):

(?=[a-zA-Z0-9#@)

I omitted the ^ here because it's already at the beggining of everything, so it's not necessary to be redundant. Now we just bring together all the lookaheads and match the valid password using .* instead of .{8,}:

^(?=[a-zA-Z0-9#@)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*

Note:

  1. Although, in the regex and examples you provided, I don't really know why: 1) #@$? were not treated as mandatory; 2) undesired characters were only allowed at the end of the string and not in another place. Maybe it has something to do with the regex engine used by AWS, because everything worked as expected when I tested it on my own.
Answer from nxnev on Stack Exchange
🌐
RegexOne
regexone.com › lesson › excluding_characters
RegexOne - Learn Regular Expressions - Lesson 4: Excluding specific characters
For example, the pattern [^abc] will match any single character except for the letters a, b, or c. With the strings below, try writing a pattern that matches only the live animals (hog, dog, but not bog). Notice how most patterns of this type can also be written using the technique from the last lesson as they are really two sides of the same coin. By having both choices, you can decide which one is easier to write and understand when composing your own patterns.
Top answer
1 of 3
3

Regex:

^(?=[a-zA-Z0-9#@)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*

Explanation:

In the regex you provided, the lookaheads serves to ensure your string met some specific conditions, but they are not the real filter which keeps out undesired strings. You specified the following conditions:

  • (?=.*?[A-Z]): Match at least one uppercase letter.
  • (?=.*?[a-z]): Match at least one lowercase letter.
  • (?=.*?[0-9]): Match at least one number.
  • (?=.*?[#@$?]): Match at least one of these characters: #@$?
  • .{8,}: Match any character at least 8 times.

But there are at least two flaws:

  • The (?=.*?[#@$?]) part is unnecessary because those special characters are meant to be optional, not mandatory[1].

  • As I said before, you did not specify a real filter, so thanks to the .{8,} part, your regex will accept any string as long as it meets the conditions established by the lookaheads, even if it has undesired special characters[1].

So to solve those flaws it is necessary to:

  • Delete the (?=.*?[#@$?]) part.

  • Add a new lookahead that acts as the filter mentioned above.

To construct this filter, you should think "which characters I want to allow?" instead of "which characters I want to disallow?", because that is a easier scenario to handle in this specific case. If you say you only want a-z, A-Z, 0-9 and #@$? to be your allowed characters, then the lookahead should look like this:

(?=[a-zA-Z0-9#@$?])

But hey, in this step you can even set the minimum length and tell the lookahead where to start and where to stop (the start and end of string in this case):

(?=[a-zA-Z0-9#@)

I omitted the ^ here because it's already at the beggining of everything, so it's not necessary to be redundant. Now we just bring together all the lookaheads and match the valid password using .* instead of .{8,}:

^(?=[a-zA-Z0-9#@)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*

Note:

  1. Although, in the regex and examples you provided, I don't really know why: 1) #@$? were not treated as mandatory; 2) undesired characters were only allowed at the end of the string and not in another place. Maybe it has something to do with the regex engine used by AWS, because everything worked as expected when I tested it on my own.
2 of 3
3

We want a lookahead anchored at the string start for each required character type as well as the length requirement. Then a simple .* to slurp it all up:

^(?=[0-9a-zA-Z#@\$\?]{8,}$)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^0-9]*[0-9]).*

Explanation:

First off, I decided to avoid use of the lazy quantifier when matching required char types (e.g. one uppercase) for the following reasons:

  • They are expensive.
  • Different regex engines have different ways of signifying lazy. (A couple don't support it at all.)
  • They aren't as common/familiar as the alternative.

So for efficiency, readability and "portability" I'm using the ^[^x]*[x] construct.

Now breaking the rest down...

^ : Everything anchored to the start

(?=[0-9a-zA-Z#@\$\?]{8,}$) : Lookahead with 8 or more of your allowed characters between start and end of string.

The next three use the same pattern: a lookahead matching zero or more of a char not matching a required char, then the required char. These are all anchored to the beginning so the effect is to allow a match of the required char at any position in the string:

(?=[^a-z]*[a-z]) : At least one lowercase.

(?=[^A-Z]*[A-Z]) : At least one uppercase.

(?=[^0-9]*[0-9]) : At least one digit.

.* : Everything above is lookahead which doesn't consume anything so consume it all here. The first lookahead makes sure the entire string is valid chars so this is safe.

I make no claims about this being optimized (except for avoiding lazy quantifier). This is simply one of the easier forms to comprehend.


Note: the cause of the problem you observed with #@$? is due to the lookahead not being anchored to the end of string. Any character will match after one of those four (and not necessarily just in the last position). Of course, you can't just add $ since that then crowds out valid characters. That's why I include all valid characters in the same lookahead.

Discussions

Regular Expression to restrict special characters
Note the ^ as the first character ... only characters that match none of the (remaining) characters in the class. ... @TedHopp oops, you're right! Although then the if clause is wrong, it gives the error message if the regex matches...... More on stackoverflow.com
🌐 stackoverflow.com
java - Regex to block certain special characters - Stack Overflow
I'm currently stuck at completing the following regex. ... and the matching structure is Sample:Te.st4:Test.Sample each name is separated with : But I want to allow the each name to have any special characters other than the following ones. More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
java - Regular expression for excluding special characters - Stack Overflow
The most useful application for ... it, and stopping the form being submitted. Note that any isolated - (not in a range) in a pattern attribute must have a preceding \ to escape it. ... When providing answers that include regex, be aware that some characters, like _ and *, ... More on stackoverflow.com
🌐 stackoverflow.com
REGEX to escape all special characters/emojies, and #hashtags from a paragraph
(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]|#[a-zA-Z]+) Toggle "Replace matches" and fill the replace box with \\$1 to escape or left it empty to remove matches. I believe the later is what you actually want to do. Edit: pattern correction. More on reddit.com
🌐 r/tasker
3
3
January 22, 2023
🌐
3SL
threesl.com › home › blog › special characters in regexes and how to escape them
Special characters in regexes and how to escape them
February 3, 2023 - If you want to match 1+2=3, you need to use a backslash (\) to escape the + as this character has a special meaning (Match one or more of the previous). To match the 1+2=3 as one string you would need to use the regex 1\+2=3
🌐
ServiceNow Community
servicenow.com › community › servicenow-ai-platform-forum › how-to-restrict-special-characters-without-restricting-spaces-in › m-p › 1066477
Solved: how to restrict special characters without restric... - ServiceNow Community
March 22, 2022 - function onChange(control, oldValue, newValue, isLoading) { if (newValue != '') { var regex = /^[a-zA-Z0-9\s]*$/; if (!regex.test(newValue)) { g_form.clearValue('title_of_the_usecase'); g_form.showFieldMsg('title_of_the_usecase', "Please only enter letters.", "error"); } } } Execution results: case 1: OK · case 2: Special character.
🌐
QBasic on Your Computer
chortle.ccsu.edu › finiteautomata › Section07 › sect07_12.html
Basic Regular Expressions: Exclusions
Rule 4. Exclusions ... except a list of excluded characters, put the excluded charaters between [^ and ]. The caret ^ must immediately follow the [ or else it stands for just itself. The character '.' (period) is a metacharacter (it sometimes has a special meaning).
🌐
ASPSnippets
aspsnippets.com › Articles › 2645 › Regular-Expression-Regex-to-exclude-not-allow-Special-Characters-in-JavaScript
Regular Expression Regex to exclude not allow Special Characters in JavaScript
December 28, 2018 - This article will illustrate how to use Regular Expression which allows Alphabets and Numbers (AlphaNumeric) characters with Space to exclude (not allow) all Special Characters. ... The following HTML Markup consists of an HTML TextBox and a Button. ... Validate JavaScript function is called. Inside the · Validate JavaScript function, the value of the TextBox is tested against the Regular Expression Alphabets and Numbers (AlphaNumeric) characters with Space.
Find elsewhere
🌐
Reddit
reddit.com › r/tasker › regex to escape all special characters/emojies, and #hashtags from a paragraph
r/tasker on Reddit: REGEX to escape all special characters/emojies, and #hashtags from a paragraph
January 22, 2023 -

Tried [^\W .] but it's doing the exact opposite, keeping the above-mentioned and getting rid of what I need. This is the paragraph:

To the Surfcasters of Florida , a lifestyle we all love and a passion that’s irreplaceable… we appreciate the support from all of you and as we continue to grow here is our very first performance fishing shirt now available at Floridasurfcasters.co Its land based fishing at its best! @floridasurfcasters 🎣• • • #FloridaSurfCasters 🎣 • • • #Snook #tarpon #trout #snapper #redfish #sheepshead #flounder #bluefish #mackerel #cubera #blackgrouper #permit #pompano #muttonsnapper #cobia #surffishing #jettyfishing #landbasedfishing #blacktip #blackdrum #jewfish #shark

[SOLUTION]

Couldn't figure a one and all solution so I've split it in parts of Variable Search Replace with regex:

  1. Remove hashtags:
    (?im)(#)\S+

  2. Remove emojis:
    \p{S}

  3. Remove unichar punctuation signs:
    \p{Po}

  4. Remove 2 empty spaces:
    \w[ ]{2,}\w

  5. Remove END PARAGRAPH unnecessary spacing
    (?m)(?<=.)\n$

Thanks u/UnkleMike, u/aasswwddd, u/Ratchet_Guy!!!!

🌐
ServiceNow Community
servicenow.com › community › itsm-forum › regex-to-exclude-numbers-and-special-character-except-quot-quot › m-p › 2352193
Regex to exclude numbers and special character exc... - ServiceNow Community
October 17, 2022 - Using that site, I came up with /[^a-zA-Z0-9-]/gm as the regex pattern. The site also provides an area to test the expression and an explanation of how it is evaluating. Match a single character not present in the list below [^a-zA-Z0-9-]
🌐
CoreUI
coreui.io › answers › how-to-remove-special-characters-from-a-string-in-javascript
How to remove special characters from a string in JavaScript · CoreUI
May 20, 2026 - Use replace() with regular expressions to efficiently remove special characters from strings in JavaScript.
🌐
regex101
regex101.com › library › FFKEcq
regex101: How do I not allow special characters, but allow space in regex?
RegEx email /^((?!\.)[\w-_.]*)(@\w+)(\.\w+(\.\w+)?)$/gim; Just playing with Reg Ex. This to validate emails in following ways The email couldn't start or finish with a dot The email shouldn't contain spaces into the string The email shouldn't contain special chars ( mailname@domain.com First group takes the first string with the name of email \$1 => (mailname) Second group takes the @ plus the domain: \$2 => (@domain) Third group takes the last part after the domain : \$3 => (.com) Submitted by https://www.linkedin.com/in/peralta-steve-atileon/
🌐
Ablebits
ablebits.com › ablebits blog › excel › regex › regex to remove certain characters or text in excel
Excel Regex to remove certain characters or text from strings
August 22, 2023 - To remove all matches, the instance_num argument is not defined: ... To strip off certain characters from a string, just write down all unwanted characters and separate them with a vertical bar | which acts as an OR operator in regexes.
🌐
xjavascript
xjavascript.com › blog › list-of-all-characters-that-should-be-escaped-before-put-in-to-regex
All Special Characters to Escape in RegEx: A Complete Guide — xjavascript.com
They enable advanced operations like: ... Escaping other characters (\). When you want to match one of these symbols literally (e.g., a dot in "file.txt" or a star in "user*123"), you must "escape" it by prefixing it with a backslash (\).
🌐
JavaScript.info
javascript.info › tutorial › regular expressions
Escaping, special characters
October 25, 2021 - If we are creating a regular expression with new RegExp, then we don’t have to escape /, but need to do some other escaping. ... The similar search in one of previous examples worked with /\d\.\d/, but new RegExp("\d\.\d") doesn’t work, why? The reason is that backslashes are “consumed” by a string. As we may recall, regular strings have their own special characters, such as \n, and a backslash is used for escaping.
🌐
xjavascript
xjavascript.com › blog › how-to-escape-regular-expression-special-characters-using-javascript
How to Escape Regular Expression Special Characters in JavaScript: Fixing Common Implementation Mistakes — xjavascript.com
Regular expressions (regex) are powerful tools for pattern matching and text manipulation in JavaScript. However, they come with a catch: certain characters have special meanings within regex syntax (e.g., `.`, `*`, `+`). If you’re working with dynamic input (like user-generated text or external ...
🌐
ServiceNow Community
servicenow.com › community › developer-forum › using-regex-to-make-special-characters-disappear-except-when-it › m-p › 2574305
Using regex to make special characters disappear except when it is a dash. How do you do that?
May 31, 2023 - Correct. All the '-' signs are removed earlier within your step 1, since these are considered to be special characters. You can modify your step 1 and include '-' in your existing regex.