[UWP] How to check if string equals to "_n_"

BitSmithy 1,256 Reputation points
2020-03-22T23:01:06.473+00:00

Hello,

How to check if string equals to expresion showed in post title, where n is number (1,2,3,4,5,6, etc).

Note, I dont want chceck if string contains such expresion, I need to konow if the string exactly equals to expresion.

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Richard Zhang-MSFT 6,921 Reputation points
    2020-03-23T03:12:42.203+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    According to your needs, you want the string to be tested to fully conform to the form _n_, with no extra strings before and after. This situation can be solved using regular expressions:

    var regex = new Regex(@"^_\d+_$");
    if(regex.IsMatch(inputString))
    {
    // do something
    }
    

    Update

    May I know the language you are using? I implemented it using C#.

    Regular expressions have a large overhead on system resources. If there are no special requirements, you can consider this method:

    public bool IsMatchNeeds(string inputString)
    {
        if (inputString.Length < 3)
            return false;
        bool isFirst = inputString.First().Equals("_");
        bool isLast = inputString.Last().Equals("_");
        if (isFirst && isLast)
        {
            string numberString = inputString.Replace("_", "");
            bool isNumber = int.TryParse(numberString, out int num);
            return isNumber;
        }
        return false;
    }
    

    Usage

    if(IsMatchNeeds(inputString))
    {
        // do something...
    }
    

    There are several ways to check if a string is a number. In addition to the regular expressions mentioned earlier, there are the following methods:

    1. Enumerable.All

    bool isNumber = numberString.All(p => char.IsDigit(p));
    

    2. Enumerable.Any

    bool isNumber = !numberString.Any(p => p < '0' || p > '9');
    

    3. int.TryParse

    bool isNumber = int.TryParse(numberString, out int number);
    

    4. for-each loop

    bool isNumber = true;
    foreach (var p in numberString)
    {
        if (p < '0' || p > '9')
        {
            isNumber = false;
            break;
        }   
    }
    

    Thanks.

    No comments

0 additional answers

Sort by: Most helpful