Psy
Psy

Reputation: 184

Regex to allow only certain special characters and restrict underscore

As the Title suggests, i want to allow only - / \ (dash, forward slash, backward slash) from special characters. Which is this regex bellow doing, but it doesn't match underscore. How can I do it?

JavaScript: /[^\w\-\/\\]/gi

.NET : ^[\w-\/\\]*$

Upvotes: 1

Views: 1972

Answers (3)

vrintle
vrintle

Reputation: 5596

I'm a bit confused between your aim and your code. So, is this what you want ?

Pattern - /[\\\/-]/g

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163632

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));
});

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

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.

Upvotes: 1

Related Questions