[英]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: 您可以更改的内容很少,尽管它们是否有意义取决于您的要求:
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.