正则表达式避免了Java中不必要的回溯

2024-03-29

你好,我是正则表达式世界的新手。我想在 Java 测试字符串中提取时间戳、位置和“id_str”字段。

20110302140010915|{"user":{"is_translator":false,"show_all_inline_media":false,"following":null,"geo_enabled":true,"profile_background_image_url":"http:\/\/a3.twimg.com\/a\/1298918947\/images\/themes\/theme1\/bg.png","listed_count":0,"favourites_count":2,"verified":false,"time_zone":"Mountain Time (US & Canada)","profile_text_color":"333333","contributors_enabled":false,"statuses_count":152,"profile_sidebar_fill_color":"DDEEF6","id_str":"207356721","profile_background_tile":false,"friends_count":14,"followers_count":13,"created_at":"Mon Oct 25 04:05:43 +0000 2010","description":null,"profile_link_color":"0084B4","location":"WaKeeney, KS","profile_sidebar_border_color":"C0DEED",

我已经尝试过这个

(\d*).*?"id_str":"(\d*)",.*"location":"([^"]*)"

如果我使用惰性量词,它会有很多回溯.*?(regexbuddy 中为 3000 步),但是锚点“id_str”和“location”之间的字符数并不总是相同。此外,如果在字符串中找不到位置,则可能是灾难性的。

我怎样才能避免 1)不必要的回溯?

and

2)更快地找到不匹配的字符串?

Thanks.


这看起来像 JSON,相信我,用这种方式解析它非常容易。

String[] input = inputStr.split("|", 2);
System.out.println("Timestamp: " + input[0]); // 20110302140010915

JSONObject user = new JSONObject(input[1]).getJSONObject("user");

System.out.println ("ID: " + user.getString("id_str")); // 207356721
System.out.println ("Location: " + user.getString("location")); // WaKeeney, KS

参考:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

正则表达式避免了Java中不必要的回溯 的相关文章

随机推荐