Click here to Skip to main content
11,802,636 members (69,185 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: VB regular-expression string , +
Am writing an app in VB.NET and I want to replace occurrences of ? with a sequential of @param1, @param2, @paramn
INSERT INTO X (a,b,c) values (?,?,?)
should become
INSERT INTO X (a,b,c) values (@param1,@param2,@param3)

Can I achieve this with regex?
Posted 11-Apr-12 15:44pm
Roliking at 12-Apr-12 1:01am
do you want to do this is sql or in code?
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Use :
Which will give you the (...) portion and then just count the number of ? chars and replace with @paramN where N is an iterator.
Espen Harlinn at 14-Apr-12 13:30pm
Good idea
VJ Reddy at 14-Apr-12 20:17pm
Good idea. 5!
RaisKazi at 14-Apr-12 22:16pm
My 5.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

One option is to split the original string at the location of ? and reconstruct using @param as shown below
Sub Main
    Dim statement As String = "INSERT INTO X (a,b,c) values (?,?,?)"
    Dim statements As String() = statement.Split("?"C)
    'Construct a stringbuilder
    Dim sb As New StringBuilder()
    For i As Integer = 0 To statements.Length - 2
        sb.AppendFormat("{0}@param{1}", statements(i), i + 1)
    sb.Append(statements(statements.Length - 1))
    Dim modifiedStatement As String = sb.ToString()
End Sub
'INSERT INTO X (a,b,c) values (@param1,@param2,@param3)
Mike Chibaka at 13-Apr-12 0:23am
Than you a million times VJ. your snippet worked wonders :)
VJ Reddy at 13-Apr-12 1:11am
You're welcome and thank you for the appreciation.
Espen Harlinn at 14-Apr-12 13:30pm
VJ Reddy at 14-Apr-12 20:10pm
Thank you, Espen Harlinn.
RaisKazi at 14-Apr-12 22:16pm
My 5.
VJ Reddy at 15-Apr-12 0:18am
Thank you, RaisKazi.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 KrunalRohit 366
1 OriginalGriff 365
2 F-ES Sitecore 295
3 Afzaal Ahmad Zeeshan 230
4 CPallini 230
0 OriginalGriff 2,950
1 Maciej Los 1,910
2 KrunalRohit 1,862
3 CPallini 1,695
4 Richard MacCutchan 1,157

Advertise | Privacy | Mobile
Web02 | 2.8.151002.1 | Last Updated 14 Apr 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100