快速正则表达式问题(我希望)。
我需要根据正则表达式从任何字符串中识别一个子字符串。
例如,采用以下字符串:
"Blogs, Joe (S0003-000292).html"
"bla bla bla S0003-000292 & so on"
"RE: S0003-000292"
我需要提取“S0003-000292”部分(如果未找到则标记异常)。
至于我尝试过的,好吧,我写了一个粗略的模式来识别 S0000-000000:
^\(S[0-9]{4}-[0-9]{6}\)$
我已经尝试过如下测试:
Dim regex As New Regex("Blogs, Joe (S0003-000292) Lorem Ipsum!")
Dim match As Match = regex.Match("^S[0-9]{4}-[0-9]{6}$")
If match.Success Then
console.writeline "Found: " & match.Value
Else
console.writeline "Not Found"
End If
但是,这总是导致未找到。
所以,真的有 2 个问题,我的模式有什么问题以及如何使用修改后的模式来提取子字符串?
(使用 .net 2)
编辑: stema 为我指明了正确的方向(即删除 ^ 和 $) - 但是这并没有解决问题,我的主要问题是我在 RegEx 构造函数中定义了字符串而不是模式 - 交换了这些并且它起作用了很好(我责怪缺乏咖啡因):
Dim regex As New Regex("S[0-9]{4}-[0-9]{6}")
Dim match As Match = regex.Match("Joe, Blogs (S0003-000292).html")
If match.Success = True Then
console.writeline "Found: " & match.Value
Else
console.writeline "Not Found"
End If
最佳答案
你必须到位 anchor ,防止您的模式从匹配
^\(S[0-9]{4}-[0-9]{6}\)$
^ ^
^
被匹配字符串的开始$
是匹配的字符串的末尾而且因为有其他的东西之前,你要匹配的部分之后,你的模式将不匹配。只是删除这些 anchor ,它应该是罚款。
或使用Word的边界,而不是
\bS[0-9]{4}-[0-9]{6}\b
\b
如果说之前和你的模式后,有一个“无字”字符(非字母或一个数字)将匹配。
关于regex - 基于正则表达式匹配提取SubString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10332832/