正则表达式提取字符串

时间:2015-04-06 11:24:49

标签: java regex

我要提取 [{“type”:“MAPPINGTYPE”,“target”:1,“source”:0},{“type”:“OWNEDOBJECTS”,“target”:3 ,“来源”:0},{“type”:“APIFILES”,“target”:2,“来源”:1}] 来自以下字符串:

String json="links":[{"type":"MAPPINGTYPE","target":1,"source":0},{"type":"OWNEDOBJECTS","target":3,"source":0},{"type":"APIFILES","target":2,"source":1}],

我使用以下代码而没有结果:

Pattern pattern = Pattern.compile("[(.*?)]");
Matcher matcher = pattern.matcher(json);
if (matcher.find())
{
   System.out.println(matcher.group(0));
}

最初的问题如下:我有一个小问题的JSON文件:

{
    "links":[{"type":"MAPPINGTYPE","target":1,"source":0},{"type":"OWNEDOBJECTS","target":3,"source":0},{"type":"APIFILES","target":2,"source":1}],
    "nodes":[{"label":["ClassDefinition","_ClassDefinition","_AbstractEntity"],"name":"HexStringParser"}],
    "links":[{"type":"MAPPINGTYPE","target":1,"source":0},{"type":"OWNEDOBJECTS","target":3,"source":0},{"type":"APIFILES","target":2,"source":1}],
    "nodes":[{"label":["ClassDefinition","_ClassDefinition","_AbstractEntity"],"name":"HexStringParser"}]
}

正如你所看到的那样,链接和节点的重叠我希望将它们合并(不删除重复)以获得这样的JSON:

{
    "links":[{"type":"MAPPINGTYPE","target":1,"source":0},{"type":"OWNEDOBJECTS","target":3,"source":0},{"type":"APIFILES","target":2,"source":1},{"type":"MAPPINGTYPE","target":1,"source":0},{"type":"OWNEDOBJECTS","target":3,"source":0},{"type":"APIFILES","target":2,"source":1}],
    "nodes":[{"label":["ClassDefinition","_ClassDefinition","_AbstractEntity"],"name":"HexStringParser"},{"label":["ClassDefinition","_ClassDefinition","_AbstractEntity"],"name":"HexStringParser"}],
}

我尝试过json解析器

Map<String,String[]> map = new HashMap<String,String[]>();
ObjectMapper mapper = new ObjectMapper();
try {
    //convert JSON string to Map
    map = mapper.readValue(json, 
    new TypeReference<HashMap<String,String[]>>(){});
    System.out.println(map);

    } catch (Exception e) {
          e.printStackTrace();
    }

但我得到了这个堆栈跟踪:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String[] out of VALUE_STRING token
 at [Source: java.io.StringReader@3d0b8bc1; line: 1, column: 219]
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219)
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:212)
    at org.codehaus.jackson.map.deser.std.PrimitiveArrayDeserializers$StringDeser.handleNonArray(PrimitiveArrayDeserializers.java:153)
    at org.codehaus.jackson.map.deser.std.PrimitiveArrayDeserializers$StringDeser.deserialize(PrimitiveArrayDeserializers.java:119)
    at org.codehaus.jackson.map.deser.std.PrimitiveArrayDeserializers$StringDeser.deserialize(PrimitiveArrayDeserializers.java:107)
    at org.codehaus.jackson.map.deser.std.MapDeserializer._readAndBind(MapDeserializer.java:319)
    at org.codehaus.jackson.map.deser.std.MapDeserializer.deserialize(MapDeserializer.java:249)
    at org.codehaus.jackson.map.deser.std.MapDeserializer.deserialize(MapDeserializer.java:33)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1870)
    at com.MyAppConverter.MapTool.HomeController.checkMapping(HomeController.java:174)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:146)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:279)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

4 个答案:

答案 0 :(得分:1)

使用模式:&#34; \\ [。* \\]&#34;

示例:

    Pattern pattern = Pattern.compile("\\[.*\\]");
    Matcher matcher = pattern.matcher(json);
    if (matcher.find())
    {
        System.out.println(matcher.group());
    }

答案 1 :(得分:0)

您需要转义[]个字符,因为[是正则表达式中的特殊字符,它指的是字符类的开头。因此,此[(.*?)]将匹配给定列表中的单个字符,无论它可能是.还是(还是*)还是?

Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher matcher = pattern.matcher(json);
if (matcher.find())
{
   System.out.println(matcher.group(0));
}

您不需要使用捕获组。

Pattern pattern = Pattern.compile("\\[.*?\\]");

OR

Pattern pattern = Pattern.compile("\\[[^\\]]*\\]");

答案 2 :(得分:0)

它看起来像JSON字符串。正确使用JacksonGSON JSON API来提取。

Tutorial

将JSON字符串转换为Map<String,String>并获取所需的字段。

String json = "{\"name\":\"mkyong\", \"age\":\"29\"}";

Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();

try {

    //convert JSON string to Map
    map = mapper.readValue(json, 
        new TypeReference<HashMap<String,String>>(){});

    System.out.println(map);

} catch (Exception e) {
    e.printStackTrace();
}

使用GSON API:

Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> map=new Gson().fromJson(json, type);
System.out.println(map.get("links"));

这是有效的JSON字符串:

{
    "links": [
        {
            "type": "MAPPINGTYPE",
            "target": 1,
            "source": 0
        },
        {
            "type": "OWNEDOBJECTS",
            "target": 3,
            "source": 0
        },
        {
            "type": "APIFILES",
            "target": 2,
            "source": 1
        }
    ]
}

答案 3 :(得分:0)

只需使用一个\来查看[]个字符,因为它们在正则表达式中保留:

\[(.*?)\]