[英]Regular expression to parse id
I'm looking for a regular expression to parse the id of a record in MongoDB: 我正在寻找一个正则表达式来解析MongoDB中记录的id:
{"$oid":"5527b117d3d511091e1735e2"}
I'm trying with the following one but it fails: 我正在尝试以下一个,但它失败了:
private static final Pattern p = Pattern.compile("\\{\"([a-zA-Z\\d]+)\"\\}");
Matcher m = p.matcher("{\"$oid\":\"5527b117d3d511091e1735e2\"}");
if(!m.find()) {
throw new IllegalArgumentException("The id should be within parenthesis and quotes.");
}
Any help ? 有帮助吗?
You need to include the key part also in the regex or just "\\\\{\\"([a-zA-Z\\\\d$]+)\\":"
because [a-zA-Z\\\\d]+
won't match the inbetween :
and there isn't a closing curly brace immediately following the key part. 你需要在正则表达式中包含关键部分或只需
"\\\\{\\"([a-zA-Z\\\\d$]+)\\":"
因为[a-zA-Z\\\\d]+
赢了不匹配inbetween :
并且在关键部分后面没有紧密的大括号。
final Pattern p = Pattern.compile("\\{\"([a-zA-Z\\d$]+)\":\"([^\"]*)\"\\}");
Matcher m = p.matcher("{\"$oid\":\"5527b117d3d511091e1735e2\"}");
if(m.find())
{
System.out.println("Key : " + m.group(1));
System.out.println("Value : " + m.group(2));
}
Output: 输出:
Key : $oid
Value : 5527b117d3d511091e1735e2
这对我有用
String id = str.replaceAll(".*\"(\\w+)\"}", "$1");
Use a JSON parser: 使用JSON解析器:
String j = "{\"$oid\":\"5527b117d3d511091e1735e2\"}";
JSONParser p = new JSONParser();
JSONObject o = (JSONObject) p.parse(j);
System.out.println(o.get("$oid"));
Output: 输出:
5527b117d3d511091e1735e2
JSON library used: 使用的JSON库:
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
<version>2.7.1</version>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.