快速RegExp问题(我希望).
我需要根据正则表达式从任何字符串中识别子字符串.
例如,请使用以下字符串:
"Blogs, Joe (S0003-000292).html"
"bla bla bla S0003-000292 & so on"
"RE: S0003-000292"
Run Code Online (Sandbox Code Playgroud)
我需要提取'S0003-000292'部分(如果没有找到则标记异常).
至于我试过的,好吧,我写了一个粗略的模式来识别S0000-000000:
^\(S[0-9]{4}-[0-9]{6}\)$
Run Code Online (Sandbox Code Playgroud)
我已经尝试过如下测试:
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
Run Code Online (Sandbox Code Playgroud)
但是,这总是导致未找到.
那么,真的有两个问题,我的模式有什么问题?如何使用修改后的模式来提取子字符串?
(使用.net 2)
编辑: stema指出我正确的方向(即放弃^和$) - 但是这并没有解决问题,我的主要问题是我在RegEx构造函数中定义了字符串而不是模式 - 交换了这些和它工作得很好(我责备缺乏caffine):
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
Run Code Online (Sandbox Code Playgroud)
您有固定的位置,以防止您的模式匹配
^\(S[0-9]{4}-[0-9]{6}\)$
^ ^
Run Code Online (Sandbox Code Playgroud)
^ 匹配字符串的开头
$ 匹配字符串的结尾
并且由于在您想要匹配的部分之前和之后还有其他内容,因此您的模式将不匹配.只需删除那些锚,它应该没问题.
或者使用单词边界
\bS[0-9]{4}-[0-9]{6}\b
Run Code Online (Sandbox Code Playgroud)
\b 如果在您的模式之前和之后存在"非单词"字符(非字母或数字),则匹配.