Want any alphanumeric and underscore, dash and period to pass
In my control开发者_Python百科ler, 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?
try this:
@"[._\w-]+"
(?:\w|[-_.])+
Will match either one or more word characters or a hyphen, underscore or period. They are bundled in a non-capturing group.
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:
Does the following help? @"[\w_-.]+"
P.S. I use Rad Software Regular Expression Designer to design complex Regexes.
@"[\w_-.]+"
im no regex guru was just a guess so verify that it works...
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.
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.
精彩评论