Saphire
Saphire

Reputation: 1930

How to extract words from structured string?

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.

Upvotes: 0

Views: 74

Answers (2)

rbm
rbm

Reputation: 3253

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();

Upvotes: 3

Rikki Gibson
Rikki Gibson

Reputation: 4347

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

Upvotes: 0

Related Questions