2017-07-11 56 views
-1

试图找出匹配正则表达式,然后从该字符串获取值。正则表达式:检查字符串表达式,然后过滤掉值

字符串值将是这样的: computerFileHardware20131211.pdf computerFileSoftware20131322.pdf computerFileEngineering20232.pdf

Regex regex = new Regex(@"computerFile[^[A-Za-z]+$]([^0-9]+)\.pdf"); 
Match match = regex.Match("computerFileHardware20131211.pdf"); 
if (match.Success) 
{ 
    Console.WriteLine(match.Value); 
} 

那么我现在要做的是确保我可以匹配正则表达式然后能够过滤掉数字值。因此,例如对于computerFileHardware20131211.pdf数值将是20131211.

我不是很好的正则表达式。我认为我的第一个障碍是搞清楚正则表达式。我在某处读到了你想要过滤掉的字符串。所以这就是为什么我有([^ 0-9] +)。

+1

可能更容易为你分割字符串与空格,然后每个项目检查它是否包含“computerFileEngineering”,并以“.pdf”结束。如果是的话 - 然后切断部分字符串? – demo

+0

感谢您的快速回复。那么每次我都可以有不同的正则表达式。我主要想过滤掉数字值。因此,检查正则表达式是否有效,然后提取数字值。 – MindGame

+1

我也有过像你这样的经历,但最终没有正则表达式:) – demo

回答

1

尝试像https://regex101.com/r/KWiAg0/1

Regex regex = new Regex(@"computerFile[A-Za-z]+([0-9]+)\.pdf"); 
Match match = regex.Match("computerFileHardware20131211.pdf"); 
if (match.Success) 
{ 
    Console.WriteLine(match.Groups[1].Value); 
} 

正则表达式中包含“子表达式”被括号括起来。 每个子表达式都形成一个组。使用Groups属性,您可以访问由正则表达式捕获的各个组。

+0

Match.Groups是如何工作的?意思是为什么match.Groups [1]给我的数字值?是否因为正则表达式中的括号?我检查了这个链接,似乎这就是为什么它这样做。 https://www.dotnetperls.com/regex-groups。对? – MindGame

+1

@MindGame我编辑了我的答案 – Alberto

+0

谢谢你清理。我看到第一组始终是你想要匹配的原始字符串。 – MindGame

0

如果你只是想更换号码:

string fileName = "computerFileHardware20131211"; 
string pattern = "[0-9]{1,}"; 
string replacement = "123"; 

Regex rgx = new Regex(pattern); 

string result = rgx.Replace(fileName , replacement); 
+0

其实我只是想从文件名中过滤出来。 – MindGame

+0

@MindGame字符串结果= rgx.Replace(fileName,''); –

相关问题