Ammar Ammar - 2 years ago 92 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
. 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 Source

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
                                                        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 " - ".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download