gpt4 book ai didi

regex - Excel 中的模式匹配计数(正则表达式和 VBA)

转载 作者:行者123 更新时间:2023-12-03 02:55:43 25 4
gpt4 key购买 nike

我有一个 Office 2007 .XLSX 文件,其中包含 5000 多条记录,如下所示(一个单元格包含多行文本)。问题:在相邻的单元格上,输入该单元格中的事件计数。查看 A1 的单元格数据,您可以看到 3 个事件:

单元格 A1:

1/15/2013 1:30:11 AM Userx
Had to reboot system
1/15/2013 1:32:11 AM Userx
System running finished rebooting and appears to be working
11/15/2013 12:30:11 AM Userx
System hung again

问题是日期值不一致。日、月和小时可以是一位数或两位数,但它们总是在新行中注明。

我的代码解决方案是获取单元格,在换行符处将其拆分,修剪最后一个“:”之后 5 个字符的所有内容,然后根据我的正则表达式评估结果。之后,一些基本的计数和文本插入到相邻的单元格中。

下面是如何调用该函数的示例。

'calling function from another source:

thecount = CountOfDateValues(Range("a1").Value) 'get count
Range("b1").Value = thecount 'put count to adjacent cell

是否有任何代码可以获取字符串值并返回与正则表达式匹配的计数?

最佳答案

您还可以使用\n 在模式表达式中包含换行符。这样,您就不必拆分数组中的文本:

Private Function String_CountRegExp_Debug()

'Input of the test text
Dim TestText As String
TestText = "1/15/2013 1:30:11 AM Userx" & vbNewLine & _
"Had to reboot system" & vbNewLine & _
"1/15/2013 1:32:11 AM Userx" & vbNewLine & _
"System running finished rebooting and appears to be working" & vbNewLine & _
"11/15/2013 12:30:11 AM Userx" & vbNewLine & _
"System hung again"

'Input of the Pattern
Dim RE_Pattern As String
RE_Pattern = "(\d{1,2})\/(\d{1,2})\/(\d{4})\s(\d{1,2}):(\d{1,2}):(\d{1,2})\s([A,P]M).*\n"

Debug.Print String_CountRegExp(TestText, RE_Pattern)

End Function

Public Function String_CountRegExp(Text As String, Pattern As String) As Long
'Count the number of Pattern matches in a string.

'Set up regular expression object
Dim RE As New RegExp
RE.Pattern = Pattern
RE.Global = True
RE.IgnoreCase = True
RE.MultiLine = True
'Retrieve all matches
Dim Matches As MatchCollection
Set Matches = RE.Execute(Text)
'Return the corrected count of matches
String_CountRegExp = Matches.Count

End Function

关于regex - Excel 中的模式匹配计数(正则表达式和 VBA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15554132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com