基于正则表达式匹配提取SubString

时间:2012-04-26 11:52:19

标签: regex vb.net

Quick RegExp问题(我希望)。

我需要根据正则表达式从任何字符串中识别一个子字符串。

例如,请使用以下字符串:

"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

然而,这总是导致未找到。

所以,真的有两个问题,我的模式有什么问题&如何使用修改后的模式提取子字符串?

(使用.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

3 个答案:

答案 0 :(得分:7)

你有固定的地方阻止你的模式匹配

^\(S[0-9]{4}-[0-9]{6}\)$
^                      ^

^匹配字符串的开头

$匹配字符串

的结尾

并且由于在您想要匹配的部分之前和之后还有其他内容,因此您的模式将不匹配。只需删除那些锚点就可以了。

或者改用字边界

\bS[0-9]{4}-[0-9]{6}\b
如果您的模式之前和之后存在“非单词”字符(非字母或数字),

\b将匹配。

答案 1 :(得分:0)

以下是可以帮助您的代码 注意:我是用c#

写的
Regex reg  = new Regex("(.)*S[0-9]{4}-[0-9]{6}(.)*");
string str = "Blogs, Joe (S0003-000292) Lorem Ipsum!";
Console.WriteLine(reg.IsMatch(str));
Console.ReadLine();

答案 2 :(得分:0)

Dim reg as new Regex("(.)*S[0-9]{4}-[0-9]{6}(.)*")
Dim str as new string("Blogs, Joe (S0003-000292) Lorem Ipsum!")
MessageBox.show(reg.IsMatch(str))


I am not sure about syntax but this may be a right conversion of my c# code.
相关问题