java正则表达式在特定值后获取值

问题描述

我有一些包含 /bot/{idBot} 的端点,我需要提取idBot

我们可以通过 java 中的正则表达式来实现吗?

以下是端点的一些示例:

/bot/6/block/30/content/text
/bot/6/block/content/input/list/option/30
/account/bot/32/language
/account/bot/6

尝试过没有成功!

Matcher m2 = Pattern.compile("/bot/(\\d+)").matcher(path);

编辑:我有一些这样的端点:

/account/checkToken
/account/checkUser

那些需要被忽略的!

谢谢!!

解决方法

您可以使用 String#replaceAll 作为正则表达式单行选项:

String input = "/account/bot/32/language";
String num = input.matches(".*/bot/\\d+.*") ? input.replaceAll(".*/bot/(\\d+).*","$1") : "";
System.out.println(num);
,

matcher.group(1) 就是你要找的。​​p>

查看下面的完整代码。

示例代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "\\/bot\\/(\\d+)";
final String string = "/bot/6/block/30/content/text\n"
     + "/bot/6/block/content/input/list/option/30\n"
     + "/account/bot/32/language\n"
     + "/account/bot/6";

final Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    System.out.println("Required match: " + matcher.group(1));
}

输出:

Full match: /bot/6
Required match: 6
Full match: /bot/6
Required match: 6
Full match: /bot/32
Required match: 32
Full match: /bot/6
Required match: 6

编辑:为了支持排除某些 API,更新了正则表达式

添加负前瞻

public static void main(String[] args) {
    final String regex = "^(?!\\/account\\/checkToken)(?!\\/account\\/checkUser).*\\/bot\\/(\\d+)";
    final String string = "/bot/6/block/30/content/text\n"
            + "/bot/6/block/content/input/list/option/30\n"
            + "/account/bot/32/language\n"
            + "/account/bot/6\n"
            + "/account/checkToken/bot/6\n"
            + "/account/checkUser/bot/78";

    final Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(string);

    while (matcher.find()) {
        System.out.println("Full match: " + matcher.group(0));
        System.out.println("Required match: " + matcher.group(1));
    }
}

输出:

Full match: /bot/6
Required match: 6
Full match: /bot/6
Required match: 6
Full match: /account/bot/32
Required match: 32
Full match: /account/bot/6
Required match: 6