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

需要正则表达式来匹配由/或字符串末尾限定的单词

  •  1
  • amadain  · 技术社区  · 8 月前

    我需要一个正则表达式来解析url中的companyid和branchid。

    问题是分支可能出现在字符串的末尾,也可能出现在该字符串的中间。它将始终跟随/分支。

    这里有两个例子:

    http://localhost:8080/customer-api/customers/1128952/branches/83370
    http://localhost:8080/customer-api/customers/1128952/branches/83370/validate
    

    其中1128952是customerid,83370是branchid

    现在我知道了

    ^.*customers/(.*?)/branches/(.*?)$ 
    

    解析出第一个示例的customerid和branchid

    ^.*customers/(.*?)/branches/(.*?)/.*$
    

    解析出第二个示例的customerid和branchid

    我的问题是,我想要一个正则表达式来解析出涵盖这两种情况的branchid。有人能帮忙吗?

    2 回复  |  直到 8 月前
        1
  •  1
  •   user24714692    8 月前

    您可以使用 (customers)\\/([^\\/\\s]+)|(branches)\\/([^\\/\\s]+) 或者简单地说 customers\\/([^\\/\\s]+)|branches\\/([^\\/\\s]+) :

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Solution {
        public static void main(String[] args) {
            final String regex = "(customers)\\/([^\\/\\s]+)|(branches)\\/([^\\/\\s]+)";
            final String string = "http://localhost:8080/customer-api/customers/1128952/branches/83370\n"
                    + "http://localhost:8080/customer-api/customers/1128952/branches/83370/validate";
    
            final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
            final Matcher matcher = pattern.matcher(string);
    
            while (matcher.find()) {
                for (int i = 1; i <= matcher.groupCount(); i++) {
                    System.out.println("Capture Group " + i + ": " + matcher.group(i));
                }
            }
        }
    }
    

    印刷品

    Capture Group 1: customers
    Capture Group 2: 1128952
    Capture Group 3: null
    Capture Group 4: null
    Capture Group 1: null
    Capture Group 2: null
    Capture Group 3: branches
    Capture Group 4: 83370
    Capture Group 1: customers
    Capture Group 2: 1128952
    Capture Group 3: null
    Capture Group 4: null
    Capture Group 1: null
    Capture Group 2: null
    Capture Group 3: branches
    Capture Group 4: 83370
    

    细节:

    • 有四个捕获组,实际上你只需要其中的两个。(另外两个只是为了清楚起见)。

    • 前两组是为客户准备的。

    • 第三个和第四个是分支。

    • ([^\\/\\s]+) 表示允许使用所有字符,但以下字符除外 \s / .

        2
  •  1
  •   The fourth bird    8 月前

    如果你只想按顺序匹配数字,你可以使用2个捕获组:

    ^.*/customers/(\d+)/branches/(\d+)\b
    

    在Java中,有两个转义符:

    String regex = "^.*/customers/(\\d+)/branches/(\\d+)\\b";
    

    Regex demo

    或者更精确地匹配协议并断言 / 在字符串的末尾:

    ^https?://\S*/customers/(\d+)/branches/(\d+)(?:/|$)
    

    模式匹配:

    • ^ 字符串开头
    • https?:// 将协议与可选s匹配,然后 ://
    • \S* 匹配可选的非空格字符
    • /customers/ 按字面意思匹配
    • (\d+)/branches/ 在中捕获1+位数字 第1组 然后 /branches/
    • (\d+)(?:/|$) 在中捕获1+位数字 第2组 要么匹配 / 或者字符串的末尾

    Regex demo

    如果你想扩大id的匹配范围,而不是 \d+ 您也可以使用 \w+ 匹配单词字符或 [^\s/]+ 匹配除以下字符以外的非空白字符 /