如何使用java Pattern在两个字符串之间提取字符串

时间:2018-02-15 11:39:42

标签: java

我有一个字符串/ subscription / ffcc218c-985c-4ec8-82d7-751fdcac93f0 / subscribe,我想从中提取中间字符串/subscription/<....>/subscribe。我写了下面的代码来获取字符串

String subscriber = subscriberDestination.substring(1);
int startPos = subscriber.indexOf("/") + 2;
int destPos = startPos + subscriber.substring(startPos + 2).indexOf("/");
return subscriberDestination.substring(startPos, destPos + 2);

回馈ffcc218c-985c-4ec8-82d7-751fdcac93f0

如何使用java Pattern库编写更好的代码?

4 个答案:

答案 0 :(得分:3)

如果你想使用正则表达式,一个简单的方法是:

return subscriber.replaceAll("/.*/([^/]*)/.*", "$1");
  • /.*/适用于/subscription/
  • ([^/]*)一个匹配所有字符的捕获组,直到下一个/
  • /.*适用于/subscribe

replaceAll的第二个论点是我们希望保留第一组。

您可以使用Pattern通过编译表达式来提高效率:

Pattern p = Pattern.compile("/.*/([^/]*)/.*"); ///store it outside the method to reuse it

Matcher m = p.matcher(subscriber);
if (m.find()) return m.group(1);
else return "not found";

答案 1 :(得分:1)

来自我的5c。我建议使用public final class Foo { private static final Pattern PATTERN = Pattern.compile(".*subscription\\/(?<uuid>[\\w-]+)\\/subscribe"); public static String getUuid(String url) { Matcher matcher = PATTERN.matcher(url); return matcher.matches() ? matcher.group("uuid") : null; } } 来提取已知格式的子字符串:

var firstArray = [
    {id:"1", name: "Shirt", price: "15.00"},
    {id:"2", name: "Pants", price: "30.00"},
    {id:"3", name: "Socks", price: "8.00"},
    {id:"4", name: "Gloves", price: "5.00"},
    {id:"5", name: "Shirt", price: "16.00" }
];

var secondArray = [
    {id:"1", name: "Shirt", price: "25.00"},
    {id:"2", name: "Pants", price: "40.00"},
    {id:"3", name: "Socks", price: "12.00"},
    {id:"4", name: "Gloves", price: "6.00"},
    {id:"5", name: "Shirt", price: "21.00"},
    {id:"6", name: "Hat", price: "30.00" }
];

RegEx Demo

答案 2 :(得分:0)

绩效可以通过以下方式得到改善:

  1. 未创建substring s。
  2. indexOf(..) char也应该比String更快

    final int startPos = subscriberDestination.indexOf('/',1) + 1 ;
    final int destPos = subscriberDestination.indexOf('/',startPos+1);
    return subscriberDestination.substring(startPos, destPos );
    
  3. 关于使用java Pattern library
    您是否期望获得任何性能提升?我怀疑你会通过使用java模式库得到一些。但我建议将其描述为绝对确定。

答案 3 :(得分:-1)

您可以使用différentéthod

String test = "abc/azerty/123";

String [] r = test.split(“/”);

您的结果在r [1]