从正则表达式中排除一些单词

时间:2018-05-04 09:53:41

标签: regex vba excel-vba excel

我有以下字符后插入空格的功能:/ -

  Private Function formatColon(oldString As String) As String

  Dim reg As New RegExp: reg.Global = True: reg.Pattern = "(\D:|\D/|\D-)"
  Dim newString As String: newString = reg.Replace(oldString, "$1 ")
  formatColon = Replace(Replace(Replace(newString, ":  ", ": "), "/  ", "/ "), "-  ", "- ")

  End Function

代码可以轻松排除日期。我想排除某些特定字符串,例如' w / d'也。 有什么办法吗?

之前abc/abc/15/06/2017 ref:123243-11 ref-111 w/d

abc/ abc/ 15/06/2017 ref: 123243-11 ref- 111 w/ d

之后

我想排除最后w / d

2 个答案:

答案 0 :(得分:4)

您可以使用(?!w/d)预测来避免将w/d与您的模式匹配:

Dim oldString As String, newString As String
Dim reg As New RegExp
With reg
 .Global = True
 .Pattern = "(?!w/d)\D[:/-]"
End With
oldString = "abc/abc/15/06/2017 ref:123243-11 ref-111 w/d"
newString = reg.Replace(oldString, "$& ")
Debug.Print newString

enter image description here

请参阅regex demo

模式详情

  • (?!w/d) - 未跟w/d
  • 的位置
  • \D - 任何非数字字符
  • [:/-] - :/-字符。

$&反向引用是指替换模式的整个匹配,不需要用捕获括号括起整个模式。

答案 1 :(得分:1)

这是另一种解决方案。

^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$