简体   繁体   English

如何从结构化字符串中提取单词?

[英]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 . 方法1返回Car Method 2 returns List/Array {door, wheel, antenna} 方法2返​​回列表/数组{door, wheel, antenna}

So in other words, I am looking for extractModel() and extractFields() . 换句话说,我正在寻找extractModel()extractFields()

I feel like RegEx is needed here, but I don't know how to tackle this problem. 我觉得这里需要RegEx ,但是我不知道如何解决这个问题。

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 http://rubular.com/r/ByLODRGVdy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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