0

Have the problem with regexp on C#. I get the list of strings (names of directory) by Directory.GetDirectories. For example:

E:\DevArea\SandBox\1122334455
E:\DevArea\SandBox\1231231231
E:\DevArea\SandBox\1231231232
E:\DevArea\SandBox\1231231233
E:\DevArea\SandBox\1231231234
E:\DevArea\SandBox\123123123123
E:\DevArea\SandBox\1231231231ddd

I need to find directories names witch consists of only 10 digits (only 10). I tried to use next:

public List<string> GetDirectoryList()
{
    var directoryList = new List<string>();
    var list = Directory.GetDirectories(sourcePath);
    foreach (var field in list)
    {
        if (checker.CheckInfo(field.Substring(field.LastIndexOf('\\') + 1)))
        {
            directoryList.Add(field);
        }
    }
    return directoryList;
}

public bool CheckInfo(string checkingInfo)
{
    string stringPattern = "[0-9]{10}";

    if (!Regex.IsMatch(checkingInfo, stringPattern))
    {
        return false;
    }

    return true;
}

As result i had list of directories names witch consist of digits, but there were the next one:

E:\DevArea\SandBox\123123123123

How can i ignore names with more than 10 digit?

3
  • (?<!\d)[0-9]{10}(?!\d) Commented Dec 3, 2019 at 21:16
  • Since you strip off the parent directories you can just add anchors to the regex ^\d{10}$ Commented Dec 3, 2019 at 21:18
  • Thanks a lot! (?<!\d)[0-9]{10}(?!\d) - is the best for my case! Commented Dec 3, 2019 at 21:47

2 Answers 2

1

It is better to do this in my case, i think:

public List<string> GetDirectoryList()
{
var directoryList = new List<string>();
var list = Directory.GetDirectories(sourcePath);
string stringPattern = "(?<!\d)[0-9]{10}(?!\d)";

foreach (var field in list)
{
    if (Regex.IsMatch(checkingInfo, stringPattern))
    {
        directoryList.Add(field);
    }
}
return directoryList;
}

Thanks for ctwheels!

Sign up to request clarification or add additional context in comments.

Comments

0

Just do it:

    public bool CheckInfo(string checkingInfo)
    {
        return Regex.IsMatch(checkingInfo, "^[0-9]{10}$");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.