melegant
melegant

Reputation: 1709

How To: Regular Expression Starting With Number/Letter between 2 and 150 length

I have been learning regular expressions and having some trouble coming up with a pattern.

The requirements are that it must start with a letter, number, # or @. After the 1st character it can contain any letter, number, #,@,- or . It's length must be at least 2, and no longer than 150. It cannot start with a space but can have a space in any position 2-150. (or 0-149 if you are thinking 0 based)

My test case is

9 Times

The full patter I am testing with is:

^[\dA-Za-z-.@#]{2,150}$

These cases work:

MichaelTest
9MichaelTest
#MichaelTest
@MichaelTest

Anything with a space is not working

Such as 9 Times

I am starting to see the issue is the space...how do I allow for a space, just not as the 1st character? (thanks TheGeneral for your tip)

Thanks! M.

Upvotes: 1

Views: 312

Answers (3)

OneCricketeer
OneCricketeer

Reputation: 191864

it must start with a letter, number, # or @

That's this

^[A-Za-z0-9@#]

After that, you should check a pattern that can contain a space, any other of the listed characters character, up to the limit-1 (since you've already checked the one starting character), then anchor with $

[ A-Za-z0-9@#.-]{1,149}$

Then, stick those together

Upvotes: 0

Shaun Luttin
Shaun Luttin

Reputation: 141622

This will work for you:

@"^[a-zA-Z\d#@][a-zA-Z\d#@\-\. ]{1,149}$"

It's possible to build this with variables and string interpolation:

var start = @"a-zA-Z\d#@";
var then = start + @"\-\. ";
var regex = new Regex($@"[{start}][{then}]{{1,149}}");

Test

Here is a little program with which to test.

using System;
using System.Text;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var start = @"a-zA-Z\d#@";
        var then = start + @"\-\. ";
        var regex = new Regex($@"[{start}][{then}]{{1,149}}");
        Test(regex);
    }

    public static void Test(Regex regex)
    {
        const int numTests = 10;
        const int stringLength = 150;
        var rand = new Random();
        var start = new string[]{"1", "a", "#", "@", };
        var then = new string[]{"1", "a", "#", "@", "-", ".", " "};
        for (var i = 0; i < numTests; ++i)
        {
            var builder = new StringBuilder(start[0]);
            for (var j = 1; j < stringLength; ++j)
            {
                var r = rand.Next() % then.Length;
                builder.Append(then[r]);
            }

            var test = builder.ToString();
            Console.WriteLine($"{test} {regex.IsMatch(test)}");
        }
    }
}

Upvotes: 1

Matt.G
Matt.G

Reputation: 3609

Try Regex: ^[\dA-Za-z@#][\dA-Za-z@#. -]{1,149}$

Demo

Explanation: First character will be any one of \dA-Za-z@# followed by at least 1 to at max 149 chars of \dA-Za-z@#. -, bringing total chars to atleast 2 to at max 150.

Upvotes: 2

Related Questions