0

I have the following string:

"select model (field1, field2, field3, ...)"

And I would like to write something that extracts the words where model and the fields are.

So for instance:

select Car (door, wheel, antenna)

Method 1 returns Car. Method 2 returns List/Array {door, wheel, antenna}

So in other words, I am looking for extractModel() and extractFields().

I feel like RegEx is needed here, but I don't know how to tackle this problem.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
Saphire
  • 1,812
  • 1
  • 18
  • 34

2 Answers2

3

This should work:

var m = "select Car (door, wheel, antenna)";
Regex r = new Regex(@"select\s+(.*)\s+\((.*)\)");
var model = r.Match(m).Groups[1].Value;
// untrimmmed:
// var fields = r.Match(m).Groups[2].Value.Split(',');
// trimmed:
var fields = r.Match(m).Groups[2].Value.Split(',').Select(s => s.Trim()).ToArray();
rbm
  • 3,243
  • 2
  • 17
  • 28
  • I'd add a `.Select(Trim).ToArray()` to trim the input. – CodeCaster Sep 05 '15 at 16:20
  • A few points on that `.Select(_ => _.Trim());`: [`_` is the syntax for an ignored parameter](http://stackoverflow.com/questions/424775/is-there-a-better-way-to-express-a-parameterless-lambda-than) (`s` would suffice), you can abbreviate it to `Select(Trim)` and you'd want this result materialized (`.ToList()` or `.ToArray()`) as you'll probably iterate it somewhere anyhow, and this would make multiple enumerations or other operations safe and possible. So please make it `.Select(Trim).ToList()` (or `ToArray()`) and you have my upvote back. ;-) – CodeCaster Sep 05 '15 at 16:22
  • 1
    I use '_' routinely - a habbit. Agree with `ToArray()` - added. But the `Select(Trim)` does not work. – rbm Sep 05 '15 at 16:36
0

Another direction to go:

select (\S*) \(([^)]*)

The second match group is a comma separated list, and you split on it.

http://rubular.com/r/ByLODRGVdy

Rikki Gibson
  • 4,136
  • 23
  • 34