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:
^(?![0-9._])(?!.*[0-9._]$)(?!.*\d_)(?!.*_\d)[a-zA-Z0-9_]+$
Explanation
^
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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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
'~^(?!\.)[\w.]*$(?<!\.)~'
See the regex demo
Details:
^
- 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:
username.match("[^\\w-_]");
[^] 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
username.match(/[^\w-_]/)
Javascript Regex restrict underscore at start and end
You may add another negative lookahead ((?!.*_$)
) and use
^(?!_)(?!.*_$)[a-zA-Z0-9_]+$
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
^[a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?$
^[a-zA-Z0-9](\w*[a-zA-Z0-9])?$
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?
use:
/^[ A-Za-z0-9_@./#&+-]*$/
You can also use the character class \w to replace A-Za-z0-9_
Related Topics
How to Partition Input Field to Appear as Separate Input Fields on Screen
How to Convert Gmt Time to Ist Time in JavaScript
How to Split a String With Multiple Separators in JavaScript
How to Wait for One Function to Finish Before Continuing
How to Convert Raw Mp3 Binary into Blob Url and Play It in Audio Tag
How to Output a Variable from JavaScript to HTML
Check If Json Response Data Is Empty
Keep Selected Dropdown Result After Refreshing Page, Jquery
How to Make One Observable Sequence Wait for Another to Complete Before Emitting
How to Get Full Path of Selected File on Change of <Input Type='File'> Using Javascript, Jquery-Ajax
How to Hide Select Options With Javascript (Cross Browser)
How to Get Checkbox Value in Angular
Regex to Find Json Values Without Quotes
How to Change Colour of Text Based on Its Value When a Page Initially Loads
Cannot Access Json Object Property Returns Undefined
Regex Pattern to Match At Least 1 Number and 1 Character in a String
How to Cancel Ongoing Http Requests When There's a New Requests in Angular 6 With Rxjs 6