[英]Regular expression to parse id
我正在尋找一個正則表達式來解析MongoDB中記錄的id:
{"$oid":"5527b117d3d511091e1735e2"}
我正在嘗試以下一個,但它失敗了:
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.");
}
有幫助嗎?
你需要在正則表達式中包含關鍵部分或只需"\\\\{\\"([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));
}
輸出:
Key : $oid
Value : 5527b117d3d511091e1735e2
這對我有用
String id = str.replaceAll(".*\"(\\w+)\"}", "$1");
使用JSON解析器:
String j = "{\"$oid\":\"5527b117d3d511091e1735e2\"}";
JSONParser p = new JSONParser();
JSONObject o = (JSONObject) p.parse(j);
System.out.println(o.get("$oid"));
輸出:
5527b117d3d511091e1735e2
使用的JSON庫:
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
<version>2.7.1</version>
</dependency>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.