Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 2939|回复: 4

[已解决]VBA正则表达式提取疑问

[复制链接]
发表于 2017-5-28 17:55 | 显示全部楼层 |阅读模式
本帖最后由 tcmsod 于 2017-5-28 17:57 编辑

原po.txt中相关字段如下:     1  GZ140301_0   0464052A                        A         42.00  ea             3.4910      USD                            146.62  25-May-17  Replace     CIF                  AIR


准备提取GZ140301_0   0464052A                        A         42.00  ea             3.4910      USD                            146.62  25-May-17,但下面的代码来提取出来的却是整行,求助高手如何写正则表达式,谢谢。


Sub potest()

Set regex = CreateObject("vbscript.regexp")

regex.Pattern = "GZ\d{6,}.+\d{2}\-\w{3}\-\d{2}"
Open ThisWorkbook.Path & "\po.txt" For Input As #1
Open ThisWorkbook.Path & "\output.txt" For Output As #2
Do While Not EOF(1)
  Line Input #1, s
  If regex.test(s) Then
     Print #2, s
  End If
Loop
Close #1, #2
Set regex = Nothing

End Sub



最佳答案
2017-5-28 20:45
Sub potest()

Set regex = CreateObject("vbscript.regexp")

regex.Pattern = "GZ\d{6,}.+\d{2}\-\w{3}\-\d{2}"
Open ThisWorkbook.Path & "\po.txt" For Input As #1
Open ThisWorkbook.Path & "\output.txt" For Output As #2
Do While Not EOF(1)
  Line Input #1, s
  If regex.test(s) Then
     Print #2, regex.Execute(s)(0)
  End If
Loop
Close #1, #2
Set regex = Nothing

End Sub

test.zip

12.22 KB, 下载次数: 5

vba-po

excel精英培训的微信平台,每天都会发送excel学习教程和资料。扫一扫明天就可以收到新教程
发表于 2017-5-28 20:45 | 显示全部楼层    本楼为最佳答案   
Sub potest()

Set regex = CreateObject("vbscript.regexp")

regex.Pattern = "GZ\d{6,}.+\d{2}\-\w{3}\-\d{2}"
Open ThisWorkbook.Path & "\po.txt" For Input As #1
Open ThisWorkbook.Path & "\output.txt" For Output As #2
Do While Not EOF(1)
  Line Input #1, s
  If regex.test(s) Then
     Print #2, regex.Execute(s)(0)
  End If
Loop
Close #1, #2
Set regex = Nothing

End Sub
回复

使用道具 举报

发表于 2017-5-28 20:47 | 显示全部楼层
感觉正则用  regex.Pattern ="GZ.+?(?=Replace)"即可
回复

使用道具 举报

 楼主| 发表于 2017-5-31 12:29 | 显示全部楼层
grf1973 发表于 2017-5-28 20:47
感觉正则用  regex.Pattern ="GZ.+?(?=Replace)"即可

谢谢,测试可用。另请教?(?=Replace)是什么意思,以前没有见过这种写法
回复

使用道具 举报

发表于 2017-5-31 13:37 | 显示全部楼层
提取“Replace”前面的东东
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-4-24 00:54 , Processed in 0.236091 second(s), 14 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表