0

I've the folllowing string and I want to split it:

"INSERT INTO test (test, test1, test2, test3) values (@test, @test1, @test2, @test3)";

The values that I want to get are the seperated @test @test1 @test2 @test3 So I can do something different with each one

This is what I currenly have so far.

string str = "INSERT INTO test (test, test1, test2, test3) values (@test, @test1, @test2, @test3)"
var pattern = @"(?<=@)[^@]*(?=>,)";
foreach (var m in System.Text.RegularExpressions.Regex.Split(str, pattern))
     {
        Console.WriteLine(m);
     }

This returns the whole string:

INSERT INTO test (test, test1, test2, test3) values (@test, @test1, @test2, @test3)

I hope some of you can help me because it's the last pin for my program to work.

6
  • The point is: how can you determine the boundaries where these values start from and end at? If you plan to use a regex, it should know where to start matching and where to end. Commented Sep 8, 2016 at 12:47
  • I can split it at @ and at , and at the @ later but still how do i do that. Commented Sep 8, 2016 at 12:50
  • Ok, try Regex.Matches(str, @"@\w+").Cast<Match>().Select(p => p.Value).ToList(). Although at this point, Kell's answer should work the same. Well, with the exception that the regex only matches word chars after @. Commented Sep 8, 2016 at 12:50
  • why not use a String.Format? .... or even better SQLParameters? Commented Sep 8, 2016 at 13:27
  • Yeah I used kells answer @WiktorStribiżew and it works perfectly Do you know where I can learn to regex like that ? Commented Sep 8, 2016 at 13:44

2 Answers 2

1

Well I'm not fond of regexes but a lot of people are, so I'll give you my answer as a good old string method:

var parameters = str.Split('@').Skip(1).Select(var=>"@" + var.Trim(new[] {',',')', ' '}));
Sign up to request clarification or add additional context in comments.

2 Comments

And my variation: str.Split(' ', '(', ')', ' ').Where(s => s.StartsWith("@")) Split takes a params array, so you don't need to bother creating an array
works perfectly and I even understand why thank you !
1

Had you try string pattern = @"@[a-zA-Z0-9]+";?

4 Comments

In the first line it returns INSERT INTO test (test, test1, test2, test3) values( second , third , 4th , 5th ) sorry it places everything on same line you need to read it like number of the row with what it returns
This seems to be working. Check here
@krw12572: Yeah, but not with Regex.Split (see Split List here).
@WiktorStribiżew Although the website didn't high light the @test, but I found it gets the @test when I browser the table tab. Too lazy to test on C#

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.