Reputation: 109
I know that VBA does not support positive lookahead/lookbehind, so I need some advice with the problem below.
I want to replace all spaces only between single characters so that A B C becomes ABC but AB C stays AB C.
ObjRegex.Pattern = "((?<=\b\w)\s(?=\w\b))"
SampleString = ObjRegex.Replace(SampleString, vbNullString)
Any help would be appreciated.
Upvotes: 1
Views: 928
Reputation: 626738
You may use
ObjRegex.Pattern = "\b(\w)\s(?=\w)\b"
SampleString = ObjRegex.Replace(SampleString, "$1" & vbNullString)
The lookbehind can be turned into a capturing group and its consumed value can be restored (put back) into the result with the $1
placeholder.
See the regex demo.
Pattern details
\b
- a word boundary(\w)
- Group 1 (referred to with $1
placeholder from the replacement pattern): a word char\s
- a whitespace(?=\w)
- a positive lookahead that requires a word char immediately to the right of the current position\b
- a word boundaryUpvotes: 2