如何使用正则表达式从以下字符串中以对象格式(不使用 POJO)仅获取给定字符串中的字段名称

How to get just the field names from the given string in object format ( not using POJO ) from the following string using regex

字符串如下:

"{
    account_number={
    type=long
    },
    firstname={
    type=text, fields={
    keyword={
    ignore_above=256, type=keyword
            }
        }
    },
    accountnumber={
    type=long
    },
    address={
    type=text, fields={
    keyword={
    ignore_above=256, type=keyword
            }
        }
    },
    gender={
    type=text, fields={
    keyword={
    ignore_above=256, type=keyword
            }
        }
    }
}"

我只需要获取这些字段的名称,即 account_number、名字、帐号、地址、性别。 Pojo class 在这里不起作用,因为对象中的内容不固定。正则表达式可能有效。有什么建议吗?

这里我已经将你的字符串转换成 JSON 然后检索了所有的键

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;


public class SOTest {

    public static void main(String args[]) {
        Set<String> keywords = new HashSet<String>();
        final String regex = "[a-z]\w*";
        String string = "{\n"
             + "    account_number={\n"
             + "    type=long\n"
             + "    },\n"
             + "    firstname={\n"
             + "    type=text, fields={\n"
             + "    keyword={\n"
             + "    ignore_above=256, type=keyword\n"
             + "            }\n"
             + "        }\n"
             + "    },\n"
             + "    accountnumber={\n"
             + "    type=long\n"
             + "    },\n"
             + "    address={\n"
             + "    type=text, fields={\n"
             + "    keyword={\n"
             + "    ignore_above=256, type=keyword\n"
             + "            }\n"
             + "        }\n"
             + "    },\n"
             + "    gender={\n"
             + "    type=text, fields={\n"
             + "    keyword={\n"
             + "    ignore_above=256, type=keyword\n"
             + "            }\n"
             + "        }\n"
             + "    }\n"
             + "}";
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);
         while(matcher.find()) {
             String gp = matcher.group();
             keywords.add(gp);
         }
         for (String keyword : keywords) {
            string = string.replace(keyword, "\""+keyword+"\"");
        }
         string = string.replace("=", ":");
         System.out.println(string);
        JSONObject jsonObject = new JSONObject(string);
        System.out.println(jsonObject.keySet());
    }
}

输出

[account_number, firstname, accountnumber, address, gender]