简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM