excel 中如何使用正则表达式函数提取或替换内容
时间:2023-06-24 06:19:24
word中自带正则表达式,不过Excel中却没有内置。可以在VBA中定义一个正则表达式函数,然后Excel中就可以调用了。VBA代码如下(VBA高亮无效,凑合着看):
1.Function ExStr(Str As String, Parttern As String, ActionID As Integer, Optional RepStr As String = "")
2. Dim regex As Object
3. Set regex = CreateObject("vbscript.regexp")
4. With regex
5. .Global = True
6. .IgnoreCase = True
7. .MultiLine = True
8. .Pattern = Parttern
9. End With
10. Select Case ActionID
11. Case 1: '替换
12. ExStr = regex.Replace(Str, RepStr)
13. Case 2: '判断
14. ExStr = regex.test(Str)
15. Case 3: '提取
16. Dim matches As Object
17. Set matches = regex.Execute(Str)
18. For Each Match In matches
19. ExStr = ExStr & Match.Value
20. Next
21. End Select
22.End Function
'正则表达式 V2
'增加:完善注释
'函数ExStr功能,根据正则表达式,替换或判断或提取字符串
'参数 str 源字符串
'参数 Parttern 正则表达式字符串
'参数 ActionID
'函数功能
'1正则方法一,替换符合正则表达式的字符,可选参数RepStr为替换值
'2正则方法二 判断是否有符合正则表达式,有返回“TRUE”,无返回“FALSE”
'3正则方法三,提取符合正则表达式的字符
'参数 Repstr 指定替换的字符,可选项,默认为空
'附常用几个正则表达式
'第二个参数Parttern为正则表达式,按规则使用即可。使用该函数会自动得到匹配结果
'例如,要提取4位数,如下调用即可:=exStr(A1,"d{4}",3)
'替换:=ExStr(B2,"d{4}",1,"0713")
'判断:=ExStr(C2,"d{4}",2)
'匹配4位数 d{4}
'
'匹配中文字符 [u4e00-u9fa5]
'匹配双字节字符(包括汉字在内):[^x00-xff]
'匹配空白行的正则表达式:ns*r
'匹配HTML标记的正则表达式:
'匹配首尾空白字符的正则表达式:^s*|s*$ 可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
'匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
'匹配网址URL的正则表达式:[a-zA-z]+://[^s]*
'匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
'匹配国内电话号码:d{3}-d{8}|d{4}-d{7} 匹配形式如 0511-4405222 或 021-87888822
'匹配腾讯QQ号:[1-9][0-9]{4,}
'匹配中国邮政编码:[1-9]d{5}(?!d)
'匹配身份证:d{15}|d{18}
'匹配ip地址:d+.d+.d+.d+
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
office 图标无法正常显示怎么修复
![](https://img.aspxhome.com/file/2023/2/16362_0s.jpg)
Word2007编辑域的技巧
![](https://img.aspxhome.com/file/2023/6/19576_0s.jpg)
Excel怎么核对表格的数据是否一致?
![](https://img.aspxhome.com/file/2023/5/a139985_0s.png)
Win10硬盘重装okldr.mbr错误启动不了解决办法
![](https://img.aspxhome.com/file/2023/6/49076_0s.png)
sumproduct函数的使用方法及实例?sumproduct函数多条件求和
![](https://img.aspxhome.com/file/2023/0/a161270_0s.png)
excel2010批量删除超链接小技巧
![](https://img.aspxhome.com/file/2023/1/a143591_0s.jpg)
Excel生产合同到期提醒:合同到期前30天 提醒将开始
![](https://img.aspxhome.com/file/2023/4/a143264_0s.png)
excel2003制作数据分析的教程
Excel表格中的地址怎么从中地方选省份并统计?
![](https://img.aspxhome.com/file/2023/8/40458_0s.png)
Excel工资表格怎么计算应缴的个税?
![](https://img.aspxhome.com/file/2023/7/39977_0s.jpg)
Excel怎么提取汉字的首字母
利用WeekNum函数 轻松知道一个日期是第多少周呢
![](https://img.aspxhome.com/file/2023/5/a155655_0s.png)
excel表格网格线怎么取消
excel横排怎么变竖排?excel单元格文字方向调整方法介绍
![](https://img.aspxhome.com/file/2023/7/41087_0s.jpg)
Word文档中怎么把小方框填黑
![](https://img.aspxhome.com/file/2023/3/31623_0s.png)
该内存不能为read怎么办
![](https://img.aspxhome.com/file/2023/4/48354_0s.png)
excel表格中日期公式的使用教程
Word怎么给图片加注释?怎么在Word图片下面插入注释
![](https://img.aspxhome.com/file/2023/0/31510_0s.jpg)
Word如何制作禁止吸烟的标志
![](https://img.aspxhome.com/file/2023/8/18258_0s.jpg)