Want any alphanumeric and underscore, dash and period to pass

ぐ巨炮叔叔 提交于 2019-12-02 21:09:34

问题


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?


回答1:


try this:

@"[._\w-]+"

                 




回答2:


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

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




回答3:


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

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




回答4:


@"[\w_-.]+"

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




回答5:


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.




回答6:


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.




回答7:


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:



来源:https://stackoverflow.com/questions/1940606/want-any-alphanumeric-and-underscore-dash-and-period-to-pass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!