我有一个调用 Python 脚本的 Java 程序,并将 Python 字典的结果作为字符串。结果将类似于:
{'27': [], '10864': [u'8344', u'7769', u'7207', u'3735']}
我想将结果解析为两个字符串表,即返回的键和值。在这个例子中我想要:
String[] keys >>>> ["27",'10864'] and
String[] values >>>> ["[]","[u'8344', u'7769', u'7207', u'3735']"]
我正在尝试用正则表达式来做,但没有取得太大的成功。谁能给出有效的解决方案?
最佳答案
你可以看到我使用的正则表达式here on regex101.com .
本质上,匹配器将遍历您的输入并检测正则表达式的所有匹配项。然后,您在 while 循环中使用 .find 方法逐个检查每个匹配项并提取信息。
您可以使用常规数组,但在我看来,如果您不确定传入输入的大小,使用 ArrayList 会更有效。
这段代码对我有用:
public static void main(String[] args)
{
String input = "{'27': [], '10864': [u'8344', u'7769', u'7207', u'3735']}";
String pattern = "('([\w]*)': (\\[[u'0-9, ]*])?)";
List<String> keys = new ArrayList<>();
List<String> values = new ArrayList<>();
//Find multiple matches in your input.
Matcher m = Pattern.compile(pattern).matcher(input);
//Goes through each match individually.
while (m.find())
{
keys.add(m.group(2));
values.add(m.group(3));
}
//To display your keys and values.
System.out.println("Keys: " + keys.toString());
System.out.println("Values: " + values.toString());
}
关于java - 用 Java 拆分 Python 字典字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685943/