感觉NET的正则有BUG?

liuyilin999 2010-07-29 09:56:07
正则表达式,多行模式
下面的代码应该有2次匹配末尾,但是只有一次??为什么??

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim matchesRegex As New Regex("ef$", RegexOptions.Multiline) '正则表达式
Dim matchesFound As MatchCollection
matchesFound = matchesRegex.Matches("ab123ef" + Chr(13) & Chr(10) + "ab234ef") '搜索所有匹配
For Each match As Match In matchesFound
MsgBox(match.Value)
Next match
End Sub

^就没有问题能够正常匹配每行开头,2次

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim matchesRegex As New Regex("^ab", RegexOptions.Multiline) '正则表达式
Dim matchesFound As MatchCollection
matchesFound = matchesRegex.Matches("ab123ef" + Chr(13) & Chr(10) + "ab234ef") '搜索所有匹配
For Each match As Match In matchesFound
MsgBox(match.Value)
Next match
End Sub

...全文
87 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
liuyilin999 2010-07-29
  • 打赏
  • 举报
回复
结贴,谢谢wuyazhe
兔子-顾问 2010-07-29
  • 打赏
  • 举报
回复
看2楼回复,解释的很清楚了。正则换为
Dim matchesRegex As New Regex("ef.?$", RegexOptions.Multiline) '正则表达式
或是
Dim matchesRegex As New Regex("ef\r?$", RegexOptions.Multiline) '正则表达式
liuyilin999 2010-07-29
  • 打赏
  • 举报
回复
谢谢,但是为什么我如果从textbox1.text中取文本还是一次:
如textbox1.text中
abcdef
1234ef

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim matchesRegex As New Regex("ef$", RegexOptions.Multiline) '正则表达式
Dim matchesFound As MatchCollection
matchesFound = matchesRegex.Matches(TextBox1.Text) '搜索所有匹配
For Each match As Match In matchesFound
MsgBox(match.Value)
Next match
End Sub
xinv19shi 2010-07-29
  • 打赏
  • 举报
回复
不会!!!
兔子-顾问 2010-07-29
  • 打赏
  • 举报
回复
或是你可以看看你原本的,修改一下表达式,在$之前再匹配一个字符,就能捕获到2行了。
Dim matchesRegex As New Regex("ef.?$", RegexOptions.Multiline) '正则表达式
第一行的行尾有\r\n,第二行的行尾没有\r\n,则直接就是$,第一行的.会捕获到一个chr(13)
兔子-顾问 2010-07-29
  • 打赏
  • 举报
回复
问题1
多行模式下,.可以捕获\n,但是不包含\r,因为原本就可以包含回车。
多行模式下,^表示行首,$表示行尾,但行尾的符号式\n,不是\r\n,文本框中是回车换行,你写的代码页是回车换行。那么第一行的ef后面就不是$,而是ef\r$。你可以试验下面的例子来验证
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim matchesRegex As New Regex("ef$", RegexOptions.Multiline) '正则表达式
Dim matchesFound As MatchCollection
matchesFound = matchesRegex.Matches("ab123ef" + vbLf + "ab234ef") '搜索所有匹配
For Each match As Match In matchesFound
MsgBox(match.Value)
Next match
End Sub

16,721

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧