mrblah
mrblah

Reputation: 103507

Want any alphanumeric and underscore, dash and period to pass

In my controller, I current set a constraint that has the following regex:

 @"\w+"

I want to also allow for underscore,dash and period.

THe more effecient the better since this is called allot.

any tips?

Upvotes: 0

Views: 5302

Answers (7)

Emma
Emma

Reputation: 27723

I guess we don't really want to add the _ to our expression here, it is already part of the \w construct, which would account for uppers, lowers, digits and underscore [A-Za-z0-9_], and

[\w.-]+

would work just fine.

We can also add start and end anchors, if you'd wanted to:

^[\w.-]+$

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"[\w.-]+";
        string input = @"abcABC__.
ABCabc_.-
-_-_-abc.
";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

C# Demo


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Upvotes: 1

deerchao
deerchao

Reputation: 10544

try this:

@"[._\w-]+"

                 

Upvotes: 2

Dave Everitt
Dave Everitt

Reputation: 17876

Pattern to include all: [_.-\w]+

You can suffix the _ \. and - with ? to make any of the characters optional (none or more) e.g. for the underscore:

[_?\.-\w]+

but see Skurmedel's pattern to make all optional.

Upvotes: 0

Don
Don

Reputation: 9661

I'd use @"[\w\-._]+" as regex since the dash might be interpreted as a range delimiter. It is of no danger with \w but if you later on add say @ it's safer to have the dash already escaped.

There's a few suggestions that have _-. already on the page and I believe that will be interpreted as a "word character" or anything from "_" to "." in a range.

Upvotes: 0

Peter
Peter

Reputation: 38465

@"[\w_-.]+"

im no regex guru was just a guess so verify that it works...

Upvotes: 0

ironic
ironic

Reputation: 8939

Does the following help? @"[\w_-.]+"

P.S. I use Rad Software Regular Expression Designer to design complex Regexes.

Upvotes: 0

Skurmedel
Skurmedel

Reputation: 22149

(?:\w|[-_.])+

Will match either one or more word characters or a hyphen, underscore or period. They are bundled in a non-capturing group.

Upvotes: 1

Related Questions