简体   繁体   English

括号内的Java正则表达式

[英]Java regex inside brackets

I need to get the following information from an xml file: 我需要从xml文件中获取以下信息:

    "abridged_cast": [
      {
        "name": "Tom Hanks",
        "characters": ["Woody"]
      },
      {
        "name": "Tim Allen",
        "characters": ["Buzz Lightyear"]
      },
      {
        "name": "Joan Cusack",
        "characters": ["Jessie the Cowgirl"]
      },
      {
        "name": "Don Rickles",
        "characters": ["Mr. Potato Head"]
      },
      {
        "name": "Wallace Shawn",
        "characters": ["Rex"]
      }
    ],

So far I have been able to cut it to: 到目前为止,我已经能够将其剪切为:

    "abridged_cast": [
     {
        "name": "Tom Hanks",
        "characters": ["Woody"]

The above is obtained using this regex: 以上是使用此正则表达式获得的:

\"abridged_cast\": \\[([^]]+)\\]

I need the regex to extend to the bottom ], but I can't seem to get it to work. 我需要将正则表达式扩展到底部],但似乎无法正常工作。 I have tried a huge number of variations with no luck. 我尝试了很多没有运气的变化。

This is a bit of a train wreck, but: 这有点火车残骸,但是:

"abridged_cast": \[(\s*\{\s*"name": "[a-zA-Z .]+",\s*"characters": \[("[a-zA-Z .]+", )*"[a-zA-Z .]+"\]\s*\}(,(?=\s*\{)|\s))*\s*\],?

See demo . 参见演示

Since the "characters" field is an array, I've allowed for multiple terms there, an example of which I included in the demo. 由于“字符”字段是一个数组,因此我在其中允许使用多个术语,该示例包括在演示中。

Note that I have just shown the raw regex; 注意,我刚刚显示了原始正则表达式; to use it in java you'll have to escape the quotes and backslashes (which I didn't have the stomach for). 要在Java中使用它,您必须对引号和反斜杠进行转义(我没有胃口)。

If you have complete and valid JSON, you can parse it with Jackson or GSON. 如果您具有完整有效的JSON,则可以使用Jackson或GSON对其进行解析。

This is data classes: 这是数据类:

public static class Role {
    private String name;
    private List<String> characters;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getCharacters() {
        return characters;
    }

    public void setCharacters(List<String> characters) {
        this.characters = characters;
    }
}

public static class Cast {
    @JsonProperty("abridged_cast")
    private List<Role> roles;

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }
}

And this is how you can parse it: 这就是您可以解析的方式:

ObjectMapper om = new ObjectMapper();
Cast cast = om.readValue(s, Cast.class);

where s is your JSON. s是您的JSON。

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

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