Regex to Allow Only Certain Special Characters and Restrict Underscore

Regex to allow only certain special characters and restrict underscore

You may add an alternative in your JS regex:

var pattern = /(?:[^\w\/\\-]|_)/g;
^^^ ^^^

See the regex demo. This pattern can be used to remove the unwanted chars in JS.

In a .NET regex, you may use a character class substraction, and the pattern can be written as

var pattern = @"[^-\w\/\\-[_]]";

See the .NET regex demo

To match whole strings that only allow -, / and \ + letters/digits, use

var pattern = /^(?:(?!_)[\w\/\\-])*$/;
var pattern = @"^[-\w/\\-[_]]*$";

See this JS regex demo and the .NET regex demo.

Here, ^(?:(?!_)[\w\/\\-])*$ / ^[-\w/\\-[_]]*$ match a whole string (the ^ and $ anchors require the full string match) that only contains word, /, \ and - chars.

NOTE: In C#, \w by default matches much more than \w in JS regex. You need to use RegexOptions.ECMAScript option to make \w behave the same way as in JS.

RegEx pattern to not allow special character except underscore

What you might do is use negative lookaheads to assert your requirements:



  • ^ Assert the start of the string
  • (?![0-9._]) Negative lookahead to assert that the string does not start with [0-9._]
  • (?!.*[0-9._]$) Negative lookahead to assert that the string does not end with [0-9._]
  • (?!.*\d_) Negative lookahead to assert that the string does not contain a digit followed by an underscore
  • (?!.*_\d) Negative lookahead to assert that the string does not contain an underscore followed by a digit
  • [a-zA-Z0-9_]+ Match what is specified in the character class one or more times. You can add to the character class what you would allow to match, for example also add a .
  • $ Assert the end of the string

Regex demo

Java | Prevent any special characters EXCEPT underscores

Your regex expression is currently allowing any characters, digits and ampersands (&). Just add an underscore to the negated set:

Pattern pattern = Pattern.compile("[^_a-zA-Z0-9&]", Pattern.CASE_INSENSITIVE);

Restrict users from inserting special character except underscore

$(function() {     var haveFirst = false;$('.alphaonly').on('keypress', function (event) {  if( $(this).val().length === 0 ) {     haveFirst = false;  }var regex = new RegExp("^[a-z0-9_]+$");var first = new RegExp("^[a-z]+$");var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);if(!first.test(key) && haveFirst == false){   event.preventDefault();   return false;}else if(regex.test(key)){   haveFirst = true;}if (!regex.test(key)) {   event.preventDefault();   return false;}}); }) 
<script src=""></script> <input name="lorem" class="alphaonly">

Regex to find not start and end with dot and allow some special character only not all

You may use


See the regex demo


  • ^ - start of string
  • (?!\.) - a . cannot be the first char
  • [\w.]* - 0 or more letters, digits, _ or . chars (replace * with + to match at least 1 char in the string to disallow an empty string match)
  • $ - end of string
  • (?<!\.) - last char cannot be .

Regex to not allow symbols except hypens and underscores

Because many of the symbols (e.g. ?, [,] ) are used as a regex symbol. You need to either escape them, or do this:


[^] means does not match character set.

\w means word character [a-zA-Z0-9]

EdBallot Edit: Fixed typo regex (was [^\\w-_], changed to [^\w\-_])

Author Edit: It should be "[^\\w-_]" because it is double quoted and should be escaped, or you can single quote or make it regex


Javascript Regex restrict underscore at start and end

You may add another negative lookahead ((?!.*_$)) and use


See the regex demo. The (?!.*_$) lookahead will fail the match if after any 0+ chars other than line break chars there is a _ at the end of the string.

Alternatively, you may use a lookaround-free pattern like


See another regex demo. This pattern matches:

  • ^ - start of string
  • [a-zA-Z0-9] - an alphanumeric char
  • ([a-zA-Z0-9_]*[a-zA-Z0-9])? - an optional sequence of

    • [a-zA-Z0-9_]* - 0 or more word chars (in JS, you may replace it with \w*)
    • [a-zA-Z0-9] - an alphanumeric char
  • $ - end of string.

Regarding the EDIT

Your patterns are out of sync with the descriptions. Considering that preset should contain a pattern to use in the replace method, try the following keeping in mind that \w matches _:

'alphanumeric-spl': '[^\\w\\s./]+', // Removes all but alnum, _ . / whitespaces
'alphanumeric-underscore': '^_+|_+$|_+(?=_)|\\W+', // Removes all _ at start/end and all _ before a _ and all but alnum and _
'numeric': '[^0-9]+', // Removes all but digits
'alpha-numeric': '[\\W_]+' // Removes all but alnum

And then

regReplace = new RegExp(filter, 'ig');

Regex to accept alphanumeric and some special character in Javascript?


/^[ A-Za-z0-9_@./#&+-]*$/

You can also use the character class \w to replace A-Za-z0-9_

Related Topics

Leave a reply