C# 从字符串中获取最后一组数字的正则表达式
这就是我目前所做的,但我没有得到正确的结果C# 从字符串中获取最后一组数字的正则表达式,c#,regex,C#,Regex,这就是我目前所做的,但我没有得到正确的结果 "abc_d1.txt" should get 0 "abc_d1_2.txt" should get 2 "abc_d1_14.txt" should get 14 "abc_d12_x2_156.txt" should get 156 您可以使用此正则表达式: string y = "tester_yg1.txt"; string patt
"abc_d1.txt" should get 0
"abc_d1_2.txt" should get 2
"abc_d1_14.txt" should get 14
"abc_d12_x2_156.txt" should get 156
您可以使用此正则表达式:
string y = "tester_yg1.txt";
string pattern = @"(\d+)(?!.*\d)";
Regex rg = new Regex(pattern);
var z = rg.Match(fullFileName).Value;
Console.WriteLine($"z is {z}");
现在z1应该包含删除了编号和扩展名的文件名。当没有数字时,它将返回不带扩展名的文件名。另一个选项是使用一组正向查找
string pattern1 = @"_\d+(?=\.\w+)|(?<!_\d+)(?=\.\w+)";
Regex rg1 = new Regex(pattern1);
var z = rg1.Replace(y, "");
string z1 = Path.GetFilename(z);
(?使用
(?
看
解释
(?<=_[^\W\d_]\d+_?)\d*(?=\.\w+$)
--------------------------------------------------------------------------------
(?“abc_d1.txt”应该得到0-正则表达式无法匹配字符串中未找到的字符!您必须将空匹配项转换为0。@PoulBak是的,我也这么认为。谢谢。如果您不介意,我可以添加一个附加问题吗?例如:“abc_d1_14.txt”如何得到相反的结果?结果应该是“abc_d1”和“abc_d12_x2_156.txt”结果应为“abc\U d12\U x2”
(?<=_[^\W\d_]\d+_?)\d*(?=\.\w+$)
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
[^\W_] any character except: non-word
characters (all but a-z, A-Z, 0-9, _),
'_'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of
the string
--------------------------------------------------------------------------------
) end of look-ahead