问题链接:How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops - Stack Overflow

Regular expressions are used for Pattern Matching.

To use in Excel follow these steps:

Step 1: Add VBA reference to "Microsoft VBScript Regular Expressions 5.5"

  • Select "Developer" tab (I don't have this tab what do I do?)
  • Select "Visual Basic" icon from 'Code' ribbon section
  • In "Microsoft Visual Basic for Applications" window select "Tools" from the top menu.
  • Select "References"
  • Check the box next to "Microsoft VBScript Regular Expressions 5.5" to include in your workbook.
  • Click "OK"

Step 2: Define your pattern

Basic definitions:

- Range.

  • E.g. a-z matches an lower case letters from a to z
  • E.g. 0-5 matches any number from 0 to 5

[] Match exactly one of the objects inside these brackets.

  • E.g. [a] matches the letter a
  • E.g. [abc] matches a single letter which can be a, b or c
  • E.g. [a-z] matches any single lower case letter of the alphabet.

() Groups different matches for return purposes. See examples below.

{} Multiplier for repeated copies of pattern defined before it.

  • E.g. [a]{2} matches two consecutive lower case letter a: aa
  • E.g. [a]{1,3} matches at least one and up to three lower case letter aaaaaa

+ Match at least one, or more, of the pattern defined before it.

  • E.g. a+ will match consecutive a's aaaaaa, and so on

? Match zero or one of the pattern defined before it.

  • E.g. Pattern may or may not be present but can only be matched one time.
  • E.g. [a-z]? matches empty string or any single lower case letter.

* Match zero or more of the pattern defined before it.

  • E.g. Wildcard for pattern that may or may not be present.
  • E.g. [a-z]* matches empty string or string of lower case letters.

. Matches any character except newline \n

  • E.g. a. Matches a two character string starting with a and ending with anything except \n

| OR operator

  • E.g. a|b means either a or b can be matched.
  • E.g. red|white|orange matches exactly one of the colors.

^ NOT operator

  • E.g. [^0-9] character can not contain a number
  • E.g. [^aA] character can not be lower case a or upper case A

\ Escapes special character that follows (overrides above behavior)

  • E.g. \.\\\(\?\$\^

Anchoring Patterns:

^ Match must occur at start of string

  • E.g. ^a First character must be lower case letter a
  • E.g. ^[0-9] First character must be a number.

$ Match must occur at end of string

  • E.g. a$ Last character must be lower case letter a

Precedence table:

Order  Name                Representation
1      Parentheses         ( )
2      Multipliers         ? + * {m,n} {m, n}?
3      Sequence & Anchors  abc ^ $
4      Alternation         |

Predefined Character Abbreviations:

abr    same as       meaning
\d     [0-9]         Any single digit
\D     [^0-9]        Any single character that's not a digit
\w     [a-zA-Z0-9_]  Any word character
\W     [^a-zA-Z0-9_] Any non-word character
\s     [ \r\t\n\f]   Any space character
\S     [^ \r\t\n\f]  Any non-space character
\n     [\n]          New line

Example 1Run as macro

The following example macro looks at the value in cell A1 to see if the first 1 or 2 characters are digits. If so, they are removed and the rest of the string is displayed. If not, then a box appears telling you that no match is found. Cell A1 values of 12abc will return abc, value of 1abc will return abc, value of abc123 will return "Not Matched" because the digits were not at the start of the string.

Private Sub simpleRegex()Dim strPattern As String: strPattern = "^[0-9]{1,2}"Dim strReplace As String: strReplace = ""Dim regEx As New RegExpDim strInput As StringDim Myrange As RangeSet Myrange = ActiveSheet.Range("A1")If strPattern <> "" ThenstrInput = Myrange.ValueWith regEx.Global = True.MultiLine = True.IgnoreCase = False.Pattern = strPatternEnd WithIf regEx.Test(strInput) ThenMsgBox (regEx.Replace(strInput, strReplace))ElseMsgBox ("Not matched")End IfEnd If
End Sub

Example 2Run as an in-cell function

This example is the same as example 1 but is setup to run as an in-cell function. To use, change the code to this:

Function simpleCellRegex(Myrange As Range) As StringDim regEx As New RegExpDim strPattern As StringDim strInput As StringDim strReplace As StringDim strOutput As StringstrPattern = "^[0-9]{1,3}"If strPattern <> "" ThenstrInput = Myrange.ValuestrReplace = ""With regEx.Global = True.MultiLine = True.IgnoreCase = False.Pattern = strPatternEnd WithIf regEx.test(strInput) ThensimpleCellRegex = regEx.Replace(strInput, strReplace)ElsesimpleCellRegex = "Not matched"End IfEnd If
End Function

Place your strings ("12abc") in cell A1. Enter this formula =simpleCellRegex(A1) in cell B1 and the result will be "abc".


Example 3Loop Through Range

This example is the same as example 1 but loops through a range of cells.

Private Sub simpleRegex()Dim strPattern As String: strPattern = "^[0-9]{1,2}"Dim strReplace As String: strReplace = ""Dim regEx As New RegExpDim strInput As StringDim Myrange As RangeSet Myrange = ActiveSheet.Range("A1:A5")For Each cell In MyrangeIf strPattern <> "" ThenstrInput = cell.ValueWith regEx.Global = True.MultiLine = True.IgnoreCase = False.Pattern = strPatternEnd WithIf regEx.Test(strInput) ThenMsgBox (regEx.Replace(strInput, strReplace))ElseMsgBox ("Not matched")End IfEnd IfNext
End Sub

Example 4: Splitting apart different patterns

This example loops through a range (A1A2 & A3) and looks for a string starting with three digits followed by a single alpha character and then 4 numeric digits. The output splits apart the pattern matches into adjacent cells by using the ()$1 represents the first pattern matched within the first set of ().

Private Sub splitUpRegexPattern()Dim regEx As New RegExpDim strPattern As StringDim strInput As StringDim Myrange As RangeSet Myrange = ActiveSheet.Range("A1:A3")For Each C In MyrangestrPattern = "(^[0-9]{3})([a-zA-Z])([0-9]{4})"If strPattern <> "" ThenstrInput = C.ValueWith regEx.Global = True.MultiLine = True.IgnoreCase = False.Pattern = strPatternEnd WithIf regEx.test(strInput) ThenC.Offset(0, 1) = regEx.Replace(strInput, "$1")C.Offset(0, 2) = regEx.Replace(strInput, "$2")C.Offset(0, 3) = regEx.Replace(strInput, "$3")ElseC.Offset(0, 1) = "(Not matched)"End IfEnd IfNext
End Sub

Results:


Additional Pattern Examples

String   Regex Pattern                  Explanation
a1aaa    [a-zA-Z][0-9][a-zA-Z]{3}       Single alpha, single digit, three alpha characters
a1aaa    [a-zA-Z]?[0-9][a-zA-Z]{3}      May or may not have preceding alpha character
a1aaa    [a-zA-Z][0-9][a-zA-Z]{0,3}     Single alpha, single digit, 0 to 3 alpha characters
a1aaa    [a-zA-Z][0-9][a-zA-Z]*         Single alpha, single digit, followed by any number of alpha characters</i8>    \<\/[a-zA-Z][0-9]\>            Exact non-word character except any single alpha followed by any single digit

S

【Excel】如何使用RegexString正则表达式相关推荐

  1. Excel自定义函数使用正则表达式详解

    http://www.111cn.net/office/excel/52912.htm 函数ExStr功能,根据正规表达式,替换或判断或提取字符串 '参数 str 源字符串 '参数 Parttern ...

  2. EXCEL中如何使用正则表达式

    正则表达式,相信大家都不陌生.但在我们最常用的办公软件EXCEL中,目前没有可直接使用正则表达式的函数(至少10版本的EXCEL没有),那么今天我就分享下如何在EXCEL中自定义正则函数. 一.提需求 ...

  3. Excel中使用正则表达式的方法

    简单介绍一下Excel中如何使用正则表达式 1.导入ExcelAPI A:下载ExcelAPI B:打开Excel-文件-工具-加载项,选择ExcelAPI,然后导入xll文件 2.正则表达式样例 举 ...

  4. 如何在单元格和循环中使用Microsoft Excel中的正则表达式(Regex)

    本文翻译自:How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops How can I use ...

  5. 使用优雅方式对参数验证进行处理

    我们在一般的接口函数开发中,为了安全性,我们都需要对传入的参数进行验证,确保参数按照我们所希望的范围输入,如果在范围之外,如空值,不符合的类型等等,都应该给出异常或错误提示信息.这个参数的验证处理有多 ...

  6. C#正则_取出标签内的内容(非贪婪)

    using System.Text.RegularExpressions; /// <summary>         /// 执行正则提取出值         /// </summ ...

  7. C# WinForm开发系列 - 开篇

    该系列主要整理收集在使用C#开发WinForm程序时候碰到的一系列问题, 平时看到大家主要使用C#来开发Asp.Net应用,这方面的文章也特别多,而关于WinForm的文章相对少很多,而自己对WinF ...

  8. Python简单操作爬取微博热搜榜(表格.xls模式存储)

    爬取热搜榜需要重点注意的是: 这里的代码是先划区分类--把标题,链接和点击数划分在一个大的集合里,存储的时候再分开. 注意提取数据的方式soup.select. requests用于将链接转化成htm ...

  9. Hbase之一月速成:Hbase的shell命令

    目录 一.命令总汇 二.需求 三.基本操作 1.创建表 2.查看表 3.删除表 1)禁用表 3)删除表 四.数据的操作 1.添加数据 2. 获取数据 3.更新数据 4.删除数据 1)删除指定列 2)删 ...

最新文章

  1. jQuery温度计,支持摄氏度华氏度同时展示
  2. Windows核心编程 第25章 未处理异常和C ++异常(下)
  3. 神奇的nginx之https支持
  4. 【网络与系统安全】关于SSL/TSL协议的分析
  5. 从零写一个编译器(完结):总结和系列索引
  6. mysql存储过程模糊查询_Mysql之存储过程“模糊查询drop表”
  7. Asp.NetCore3.1开源项目升级为.Net6.0
  8. 使用不可变对象创建值对象
  9. JavaFX列表示例
  10. TextRank算法可以用来从文本中提取关键词和摘要(重要的句子)
  11. python3 xpath_「手把手教python3接口自动化」:非结构化数据提取(二)
  12. 使用Executor管理Thread对象详解
  13. AI发来贺电,您的2333号奶牛已进入恋爱时节 | 野性的呼唤
  14. XDOC云服务API(二)
  15. IDEA操作 名字快速驼峰等操作
  16. 1.4 Documents,Fields和Schema设计--目录
  17. 【快代理】隧道代理使用教程
  18. itext 生成 PDF
  19. 2016年轻人消费洞察
  20. java 批量读取excel表格内容_java 使用POI批量导入excel数据

热门文章

  1. js去掉最后一个逗号
  2. c语言表示时间的程序,C语言显示“当前时间”小程序
  3. 计组高分笔记:【05】中央处理器 「CPU细节 | 取指周期 | 间址周期 | 执行周期 | 中断周期 | 数据通路 | 硬布线控制器 | 微程序控制器 | 指令流水线 | LOAD | STORE」
  4. Redis各版本的特性及架构
  5. 如何通过纯javascript实现表单提交
  6. mongoDB Ops Manager
  7. fpc软性线路板生产工艺
  8. mac下安装node.js6 ,【并使用zsh】
  9. 停止抱怨的力量是多么强大!
  10. 白帽子守护网络安全,高薪酬成大学生就业首选!