Regex to Match and Keep Distance Between Non-Printing Text Characters

Mansour_Dalir 2,016 Reputation points
2025-02-01T18:09:30.7266667+00:00

How can the distance between non-printing text characters be matched and kept to less than 2 characters long using regex?

Dim LenSpace As Integer = 2
Dim sttTest As String = "[A A]     [AA BB]    [SS UU POPO SS]    [GAB]" & vbTab & "  [ZZZZ]"
 Dim patt As String = "(?<=\S)\s{" & LenSpace & ",}(?=\S)"
Dim regMath As MatchCollection = Regex.Matches(sttTest, patt)

The expected result should contain matches like:

  • [A A]
  • [AA BB]
  • [SS UU POPO SS]
  • [GAB]
  • [ZZZZ]

But I see the opposite of what I expected in the output. Expecting an array output of 5 text elements, but I see 4 empty space elements.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,783 questions
{count} votes

Accepted answer
  1. Viorel 120.1K Reputation points
    2025-02-02T12:56:27.3533333+00:00

    Try this:

    Dim regMatch As MatchCollection = Regex.Matches(sttTest, "\S.*?(?=\s{" & LenSpace & ",}|\s*$)")
    

    Regex.Split can be used too.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.