代码之家  ›  专栏  ›  技术社区  ›  letthefireflieslive

使用regex提取部分内容

  •  0
  • letthefireflieslive  · 技术社区  · 7 年前

    我在试着提取 14-A2F型 由于 (匹配til / PGUID/CT-14-A2F2 (行末匹配)

        final Pattern pattern = Pattern.compile("CT-[a-zA-Z0-9-\\-]+(/|\\z)");
        final Matcher matcher = pattern.matcher("P‡GUID/CT-14-A2F2/SU-14-1F939");
    
        matcher.find();
        matcher.group();
    

    3 回复  |  直到 7 年前
        1
  •  1
  •   The fourth bird    7 年前

    在你的正则表达式中 CT-[a-zA-Z0-9-\\-]+(/|\\z) 你匹配 CT-[a-zA-Z0-9-\\-]+ matcher.group(); 你将得到整个比赛 CT-14-A2F2/

    您可以将捕获组移到第一部分,然后在代码中引用第一个捕获组:

    CT-([a-zA-Z0-9-\-]+)(?:/|\z)

    CT-([a-zA-Z0-9-\\-]+)(?:/|\\z)

    final Pattern pattern = Pattern.compile("CT-([a-zA-Z0-9-\\-]+)(?:/|\\z)");
    final Matcher matcher = pattern.matcher("P‡GUID/CT-14-A2F2/SU-14-1F939");
    
    matcher.find();
    System.out.println(matcher.group(1)); // 14-A2F2
    

    Demo

        2
  •  1
  •   Matt.G    7 年前

    试试正则表达式: (?<=CT-)[a-zA-Z0-9-\\]+(?=\/|$)

    Demo

        3
  •  0
  •   Randeep Singh    7 年前

    这个正则表达式将匹配两个正斜杠之间的所有内容。 把括号里的那一组去掉。

    /([^/]*)/