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.