我正在尝试找出确定一个字符串是否以4个数字结尾的最佳方法。这些数字的范围应该是0000-9999。
例如,我有一个字符串可以是"MVI_2546"或者"FILETEST"之类的东西。
我需要解析该字符串,并根据它是否恰好以4个数字结尾返回true
或false
值。
Regex.Match
可以用来测试一个字符串是否符合一个正则表达式。它返回一个Match对象,其中Success属性表示是否匹配成功。
Regex.Match
可用於測試字串是否符合正則表達式,返回的是一個Match對象,其中Success屬性表示是否匹配成功。
Regex.Match(yourString, @"\d{4}$").Success
在你的测试中使用这个代码,以查看yourString
是否以四位数字结尾。
敬礼
Regex
,您需要使用 using System.Text.RegularExpressions
。 - Sk1X1试试这个:
\d{4}$
\d
匹配任意数字,{4}
表示前面的项(即 4
个数字)必须出现 4
次,而 $
表示字符串末尾。
下面是使用 $
的一个例子:
# RegEx foo
foo # Match
barfoo # Match
foobar # Match
# RegEx foo$
foo # Match
barfoo # Match
foobar # No Match
以下是具体步骤:
string str = "MVI_2546";
bool match =
str.Length >= 4 && //Make sure that the string has at least 4 characters
str.Substring(str.Length - 4) //Check that the last 4 characters
.All(char.IsDigit); //are all digits.
截取字符串的最后4个数字
尝试将这些数字转换为整数
如果抛出错误 -> 最后4位数字不是数字 如果成功 -> 最后4位数字是一个数字,您可以使用该整数。
\b(\d\d\d)\b
C:\\Users\\UKS\\Desktop\\New folder\\004 // true
C:\\Users\\UKS\\Desktop\\New folder\\005 // true
C:\\Users\\UKS\\Desktop\\New folder\\00478 // false
Regex.Match(yourString, @"\d{4}$").Success
- SamWhan