Killgnom
Killgnom

Reputation: 150

How to use vbNewLine in RegExp with Visual Basic

I have a problem regarding the deletion of extensively used vbNewLine's in arbitrary text with Visual Basic.

What I want basically is: When there are more then two vbNewLine after another delete all but the first two of them.

For Example:

This is some sample text.

It contains a lot of new lines.



Too much in fact.

Should boil down to:

This is some sample text.

It contains a lot of new lines.

Too much in fact.

Code Example:

Dim testText : testText = "This is some sample text." & vbNewLine &  vbNewLine & "It contains a lot of new lines." & vbNewLine & vbNewLine & vbNewLine & vbNewLine & "Too much in fact."

Dim objRegExp
Set objRegExp = New RegExp

objRegExp.Pattern = "" & "vbNewLine" & "{2,}"
'objRegExp.Pattern = "" & "vbNewLine" -> Works for single vbNewLine's
'objRegExp.Pattern = "" & "vbNewLine" -> Works for multiple instances of a (aa, aaa, aaaa, etc.)

Dim result : result = objRegExp.Replace(testText, vbNewLine)

However my pattern seems to be wrong. If I use "" & "vbNewLine" as pattern, I can replace each single newline. And when I use "a{2,}" I can replace any number of a's >= 2 which is exactly what I want, but for vbNewLines. However the code above does not work. Any suggestions on how to proceed? Using "\r\n" has not yet helped me...

Upvotes: 1

Views: 373

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

Use the following expression:

(\r?\n)(?:\r?\n){2,}

and replace with $1$1. See the regex demo.

In code:

objRegExp.Pattern = "(\r?\n)(?:\r?\n){2,}"
objRegExp.Global = True

and then

Dim result : result = objRegExp.Replace(testText, "$1$1")

The Global should be True to replace all non-overlapping instances.

Pattern details:

  • (\r?\n) - Capturing group 1 matching an optional vbCr and then a vbLf
  • (?:\r?\n){2,} - 2 or more sequences of the pattern used in Group 1.

The $1 is a backreference to the line break captured within Group 1.

If you want to hard code the line break, use vbCrLf & vbCrLf in the replacement. Or any other line break style you need.

Upvotes: 1

Related Questions