简体   繁体   English

使用Regex(Java)在对象中生成值

[英]Making values in to objects using Regex (Java)

I have some data that looks like this 我有一些看起来像这样的数据

myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}
myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}
myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}

And I'm wondering what the best way to create a bunch of objects from it would be. 我想知道从中创建一堆对象的最佳方法是什么。 I've written the following regex to extract all the values from a particular Key... 我写了以下正则表达式来提取特定键的所有值...

Pattern p_keyone            = Pattern.compile("keyone:\"(.+?)\"\\,"); 
Matcher match_keyone    = p_keyone.matcher(string);

while(match_keyone.find()) {      
    myobjects.add(new MyObject(match_keyone.group(1));
}

Which gives me a bunch of objects with a single argument... 这给了我一堆带有单个参数的对象...

myobjects.add(<valueone>);

Is there a way I can execute a single regex query and create a bunch of objects with all the values as arguments in one go. 有没有一种方法可以执行单个正则表达式查询并一次性创建一堆具有所有值作为参数的对象。 Like this... 像这样...

new MyObject( <valueone>, <valuetwo> , <valuethree> );

Thanks 谢谢

Your approach is not bad. 您的方法还不错。

Few things you could change, though it depends on your requirements whether they make sense: 您可以更改的内容很少,尽管它们是否有意义取决于您的要求:

  • Create a "Factory" class which takes 1 line of data and creates the object. 创建一个“ Factory”类,该类接受1行数据并创建对象。
  • Read the data line by line, for each line use the Factory to create it. 逐行读取数据,对于每一行,请使用Factory进行创建。
  • Depending on how fancy (and error-prone) you want it to get, you could even read the names of the objects and properties and then use reflection to create instances and set the properties. 根据您希望它获得花式(且容易出错)的方式,甚至可以读取对象和属性的名称,然后使用反射来创建实例并设置属性。

String.split() could help: String.split()可以帮助:

 String line = "myobject{keyone:\"valueone\",keytwo:\"valuetwo\",keythree:\"valuethree\"}"
             // ^-----[0]------^  ^--[1]-^  ^--[2]-^  ^--[3]-^  ^--[4]---^  ^--[5]---^  ^[6]
 String[] parts = line.split("\"");
 MyObject myObject = new MyObject(parts[1], parts[3], parts[5]);

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

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