【发布时间】:2021-05-09 02:07:13
【问题描述】:
我正在处理“如何在 Microsoft Excel 中使用正则表达式 (Regex) 中的单元格和循环”中提供的优秀信息,但是我在试图保持匹配的表达式时遇到了困难,而不是比不匹配的部分:
当在电子表格中使用该函数时,“2022-02-14T13:30:00.000Z”将转换为“T13:30:00.000Z”而不是“2022-02-14”。下面列出的代码取自“如何在 Microsoft Excel 中使用正则表达式 (Regex),包括 in-cell 和 loops”。我虽然否定 strPattern2 会起作用,但我仍然遇到问题。非常感谢任何帮助。
Function simpleCellRegex(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strPattern2 As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String
strPattern = "^T{0-9][0-9][:]{0-9][0-9][:]{0-9][0-9][0-9][Z]"
strPattern2 = "^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])"
If strPattern2 <> "" Then
strInput = Myrange.Value
strReplace = ""
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern2
End With
If regEx.test(strInput) Then
simpleCellRegex = regEx.Replace(strInput, strReplace)
Else
simpleCellRegex = "Not matched"
End If
End If
End Function
【问题讨论】:
-
你为什么用
strPattern2而不是strPattern?您正在替换没有匹配的内容,因此导致您清除字符串的日期部分。 -
旁注 - 您在
strPattern2上的 If 语句也是不必要的,因为它永远不会是“”。 -
[-.];您的正则表达式也无法正确验证日期。以二月为例,尝试给它 31 天。然后是闰年。我猜它要么编写一个复杂的正则表达式,要么做出(并陈述)一些假设。
标签: excel regex vba regex-negation