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.
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.
Maybe I didn't get your purpose but can you just use this:
if (yourString == $"_{n.ToString()}_")
{
}
or
if (yourString.Equals($"_{n.ToString()}_")
{
}
or
if (string.Equals(yourString, $"_{n.ToString()}_"))
{
}
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.
10 people are following this question.
How to write and read multiple types of data using Data Writer and Data Reader
Consuming UWP mail api from WPF Desktop Bridge App
Get Network usage information in UWP apps
How to Get/Set Cookies in Windows.Web.Http API
Switch the ListView Datatemplate from one data template to another data template?