Home > Software engineering >  How do I properly set a Regex
How do I properly set a Regex

Time:02-28

currently I am working on an input field and I want to control the given input.

To set input characters I am using a Regex.

I only want to allow all numbers, letter (capital and normal),"-", ".".

My Regex looks like this in C#:

Regex regex = new Regex(@"[\w.-] $");

Am I overseeing something?

CodePudding user response:

It looks fine, but you only check end of string not start, should add ^ at beginning. In \w also "_" is valid character, which might give you unexpected results, you could replace it with [a-zA-Z0-9]

Regex regex = new Regex(@"^[a-zA-Z0-9.-] $");

CodePudding user response:

You need regex like,

Code

Regex regex = new Regex("^[a-zA-Z0-9.-] $");

Description:

  • ^: Beginning of the string

  • [a-zA-Z0-9.-]: [] match character in below range,

    • a-z: Matches any character in lower case a to z
    • A-Z: Matches any character in UPPER case A to Z
    • 0-9 : Matches any character in a range 0 to 9
    • .- : Consider special chars .- in character range.
  • : Consider one or more characters in a given string.

  • $: End of string.


In your case, you did not define ^, which allow regex to verify at the beginning of the string. Combination of ^ and $ allow regex to check entire string. Currently your Regex is allowed to check only end of the string.

Use of \w matches word character including _. In your case, you want to check all numbers, letter (capital and normal),"-", ".". not an underscore.

  • Related