我想检索这样的字符串格式的值:
public var any:int = 0;
public var anyId:Number = 2;
public var theEnd:Vector.<uint>;
public var test:Boolean = false;
public var others1:Vector.<int>;
public var firstValue:CustomType;
public var field2:Boolean = false;
public var secondValue:String = "";
public var isWorks:Boolean = false;
我想将字段名称,类型和值存储在自定义类Property中:
public class Property
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
并使用Regex表达式获取这些值。
我能怎么做 ?
谢谢
编辑:我尝试了此,但我不知道如何使用vector..etc
/public var ([a-zA-Z0-9]*):([a-zA-Z0-9]*)( = \"?([a-zA-Z0-9]*)\"?)?;/g
最佳答案
好的,发布基于正则表达式的答案。
您的正则表达式-/public var ([a-zA-Z0-9]*):([a-zA-Z0-9]*)( = \"?([a-zA-Z0-9]*)\"?)?;/g
-包含正则表达式定界符,C#不支持它们,因此将它们视为文字符号。您需要删除它们并使用修饰符g
,因为要在C#Regex.Matches
中获得多个匹配项,或者可以使用带有Regex.Match
和while
/ Match.Success
的.NextMatch()
。
我正在使用的正则表达式是(?<=\s*var\s*)(?<name>[^=:\n]+):(?<type>[^;=\n]+)(?:=(?<value>[^;\n]+))?
。包含换行符是因为否定的字符类可以匹配换行符。
var str = "public var any:int = 0;\r\npublic var anyId:Number = 2;\r\npublic var theEnd:Vector.<uint>;\r\npublic var test:Boolean = false;\r\npublic var others1:Vector.<int>;\r\npublic var firstValue:CustomType;\r\npublic var field2:Boolean = false;\r\npublic var secondValue:String = \"\";\r\npublic var isWorks:Boolean = false;";
var rx = new Regex(@"(?<=\s*var\s*)(?<name>[^=:\n]+):(?<type>[^;=\n]+)(?:=(?<value>[^;\n]+))?");
var coll = rx.Matches(str);
var props = new List<Property>();
foreach (Match m in coll)
props.Add(new Property(m.Groups["name"].Value,m.Groups["type"].Value, m.Groups["value"].Value));
foreach (var item in props)
Console.WriteLine("Name = " + item.Name + ", Type = " + item.Type + ", Value = " + item.Value);
或使用LINQ:
var props = rx.Matches(str)
.OfType<Match>()
.Select(m =>
new Property(m.Groups["name"].Value,
m.Groups["type"].Value,
m.Groups["value"].Value))
.ToList();
和类的例子:
public class Property
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public Property()
{}
public Property(string n, string t, string v)
{
this.Name = n;
this.Type = t;
this.Value = v;
}
}
关于性能的注意事项:
正则表达式不是最快的,但是它肯定比另一个答案要快。这是在regexhero.net处执行的测试:
关于c# - 提取格式化字符串中的一些值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32346421/