Manu Mohan
Manu Mohan

Reputation: 177

Exclude some words from regular expression

I have function which inserts space after characters like : / -

  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

The code excludes dates easily. I want to exclude some a particular strings like 'w/d' also. Is there any way?

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

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

i want to exclude last w/d

Upvotes: 2

Views: 853

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use a (?!w/d) lookahead to avoid matching w/d with your pattern:

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

See the regex demo.

Pattern details

  • (?!w/d) - the location not followed with w/d
  • \D - any non-digit char
  • [:/-] - a :, / or - char.

The $& backreference refers to the whole match from the replacement pattern, no need to enclose the whole pattern with the capturing parentheses.

Upvotes: 4

niya panchal
niya panchal

Reputation: 91

Here is another solution.

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

Upvotes: 1

Related Questions