Keep it simple. Only allow underscore and alphanumeric regex:
/^[a-zA-Z0-9_]+$/
Javascript es6 implementation (works for React):
const re = /^[a-zA-Z0-9_]+$/;
re.test(variable_to_test);
Answer from GavinBelson on Stack OverflowKeep it simple. Only allow underscore and alphanumeric regex:
/^[a-zA-Z0-9_]+$/
Javascript es6 implementation (works for React):
const re = /^[a-zA-Z0-9_]+$/;
re.test(variable_to_test);
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
Restrict users from inserting special character except underscore
Matching any character except an underscore using Regex - Stack Overflow
php - Regular Expressions: How to Express \w Without Underscore - Stack Overflow
Regex doesn't recognize underscore as special character - Stack Overflow
$(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">
Try this https://regex101.com/r/3mtS4t/1
This regex ^[A-Za-z0-9_]+$ will allow only name with underscores.
/^[^_]+$/ would match a string of 1 or more character containing any character except underscore.
If I understand what you're asking for - matching strings of characters, except for strings of characters that contain an underscore - this requires regex lookahead.
The reason is that regular expressions normally operate one character at a time. So if I want to know if I should match a character, but only if there is not an underscore later, I need to use lookahead.
^((?!_)[A-Za-z0-9])+$
?! is the negative lookahead operator
EDIT:
So you want there to be at most one underscore in the portion before the @ sign, and no underscore in the portion after?
^[A-Za-z0-9]+_?[A-Za-z0-9]+@[A-Za-z0-9]+\.(com|ca|org|net)$
This portion of the regex seems to be looking for special characters:
(?=.*[!@#$%^&*-])
Note that the character class does not include an underscore, try changing this to the following:
(?=.*[_!@#$%^&*-])
You will also need to modify or remove this portion of the regex:
(?=.*\W+)
\W is equivalent to [^a-zA-Z0-9_], so if an underscore is your only special character this portion of the regex will cause it to fail. Instead, change it to the following (or remove it, it is redundant since you already check for special characters earlier):
(?=.*[^\w_])
Complete regex:
/(?=^.{8,}$)(?=.*[_!@#$%^&*-])(?=.*\d)(?=.*[^\w_])(?![.\n])(?=.*[a-z])(?=.*[A-Z]).*$/
This one here works as well. It defines a special character as by excluding alphanumerical characters and whitespace, so it includes the underscore:
(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[\d])(?=.*?[^\sa-zA-Z0-9]).{8,}
Wondering if there is a clean way to do this where you could use \W instead of spelling out every one of the allowed special characters.
[A-Za-z0-9@!#$%&*()_+-=//.,";:{}|...etc etc] for example, is so ugly but it works to exclude spaces from a password validation while allowing other special characters, letters, and numbers.
I have not been successful in finding a way to neaten it up to [A-Za-z0-9\W] with something short and sweet to say "except for spaces" at the beginning, middle, end.
Any thoughts? Thanks!
This should make it:
"^[A-Za-z_-][A-Za-z0-9_-]*$"
[A-Za-z_-] means a letter or underscore or hyphen
[A-Za-z0-9_-]* is the same, but allows numbers too
So this will allow letters, underscores, hyphens, and numbers, but no numbers at the start.
Looking at your valid input example Account-Numbers_2010 | NewMoney | test_data | a1B2-c3_d4_5e-6f, you may want to also allow spaces and |. This one allows them:
"^[A-Za-z_ |-][A-Za-z0-9_ |-]*$"
This one correctly matches Account-Numbers_2010 | NewMoney | test_data | a1B2-c3_d4_5e-6f and not 2010_Account_Numbers | New$Money | %test*data | 1aB2.
You need 2 parts to the regex. The first character, and then the rest.
^[a-zA-Z_-][a-zA-Z0-9_-]*$
This says:
Start with any character from
a-zorA-Zor_or-. And then follow that by any alphanumeric character or_or-.
Here's a simple replacement for your function based on regular expressions:
function blockSpecialChar(e) {
return /[^A-Za-z0-9._]/.test(e);
}
See it working: https://jsfiddle.net/utt3sf6p/
If you want to use keycodes instead of a regular expression, you have to use the correct keycode function getCharAt() and change your boolean expression a bit:
function blockSpecialChar(e) {
var k = e.charCodeAt(0);
return ((k > 64 && k < 91) || (k > 96 && k < 123) || (k >= 48 && k <= 57) || (k == 46) || (k == 95));
}
See it working: https://jsfiddle.net/wfn37pu6/
Note: The examples assume that e contains a single character. If e is a keyboard event (like onkeypress) instead, you have to replace .test(e) with .test(e.key) and e.charCodeAt(0) with e.key.charCodeAt(0).
/^[ A-Za-z0-9_@./#&+-]*$/
Link You can also use the character class \w to replace A-Za-z0-9_ enter link description here
You can put your special characters in a Regex pattern, then remove all special characters from your text by using the Replace method.
var regex = new Regex("[!@#$%\^&*\(\)-+=\/\\\{\}\[\]\|:;\"'<>,.\?\~`;]");
var result = regex.Replace("Some!D#Text_With%Special$Character", string.Empty);
The result would be "SomeText_WithSpecialCharacter".
The below example will remove all special characters except: (space) and _.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var regex = "[^0-9A-Za-z_ ]";
var importName = "54 w/% some_ text 999";
Console.WriteLine("Before result: " + importName);
var result = Regex.Replace(importName, regex, string.Empty);
Console.WriteLine("After result: " + result);
}
/*
//var allNeedToBeRemoved = @"!@#$%^&*()-+={}|\\:;\"'<>,.?/";
var regex = "[^0-9A-Za-z_ ]";
//var regex = new Regex("[!@#$%^&*()+{|:;'<>,.?/~`\\/=-}]");
//var regex = new Regex("[!@#$%^&*()+{|:;'<>,.?/~`\\/=-}]");
//var regex = new Regex("[!@#$%^&*()+-]");
*/
}
Put _ and . to the negated set of characters ([^...]):
$string = preg_replace('/[^a-zA-Z0-9_.]/', '', $string);
You should not omit $string = .. because preg_replace return replaced string. It does not change the string in place.
You can use some php filter widget like Purifier (to set a whitelist for input)...
But Still, we would like to suggest you to learn regex!
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.
If you want to allow only dash, forward slash and backward slash, then you could omit the ^. It means a negated character class.
You could use \w to also match and underscore and add the hyphen as the first character in the character class.
/[-\w/\\]/g
To match the whole string you could use a quantifier + for the character class to match one or more times and begin ^ and end $ of the string anchors:
^[-\w/\\]+$
Regex demo
const regex = /^[-\w/\\]+$/g;
const strings = [
"test2_/\\",
"test2$_/\\"
];
strings.forEach((str) => {
console.log(str.match(regex));
});