Ammar Ammar - 3 months ago 8
Vb.net Question

How can I check it with regular Expression?

I have a long input string that contains certain field names in-bedded in it. For instance:

SELECT some-name, some-name FROM [some-name] WHERE [some-name] = 'some-name'


The actual field name may change, but it is always in the form of
word-word
. I need to perform a regex replace on the string so that the output will look like this:

SELECT some - name, some - name FROM [some-name] WHERE [some-name] = 'some - name'


In other words, when the field name is enclosed in square-brackets, it should be left untouched, but when it is not, spaces should be inserted on either side of the dash.

Answer

You may match and capture the [...] substrings and then only match hyphens that are not surrounded with hyphens to replace them:

Dim nStr As String = "SELECT 'some-name' FROM [some-name]"
Dim nResult = Regex.Replace(nStr, "(\[[^]]+])|(?<!\s)-(?!\s)", New MatchEvaluator(Function(m As Match)
                                                   If m.Groups(1).Success Then
                                                       Return m.Groups(1).Value
                                                    Else
                                                        Return " - "
                                                     End If
                                                   End Function))

enter image description here

So, what is happening is:

  • (\[[^]]+]) - matches and stores the value of [...] substring inside the Group(1) buffer
  • (?<!\s)-(?!\s) - matches any hyphen not preceded ((?<!\s)) or followed ((?!\s)) with whitespace. Actually, we may even use \s*-\s* here to remove any whitespace there is to make sure we just insert 1 space before and after -.

If Group 1 matches, then we just re-insert it (Return m.Groups(1).Value), else we insert the space-enclosed hyphen Return " - ".

Comments