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'
SELECT some - name, some - name FROM [some-name] WHERE [some-name] = 'some - name'
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))
So, what is happening is:
(\[[^]]+])- matches and stores the value of
[...]substring inside the
(?<!\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 " - ".