java - 如何使用正则表达式提取此模式的子字符串

标签 java regex substring

我必须提取 /? 之间的字符串,即 exampleproduct

https://local.host.com/order/faces/Home/myorder/exampleproduct?_adf.ctrl-state=mfun9p14r_19

如何为此编写正则表达式 我正在使用这个逻辑,但我无法

 private static String extractPageNameFromURL(String urlFull) {    
    if (urlFull != null) {
        Pattern pattern = Pattern.compile("/(.*?).jspx?");
        Matcher matcher = pattern.matcher(urlFull);
        while (matcher.find()) {
            String str1 = matcher.group(1);
            String[] dataRows = str1.split("/");
            urlFull = dataRows[dataRows.length - 1];
        }
    }
    return urlFull;
}


 public static void main(String[] args) {
 System.out.println(DtmUtils.extractPageNameFromURL("https://local.host.com/order/faces/Home/myorder/exampleproduct?_adf.ctrl-state=mfun9p14r_19"));

}

谢谢 拉杰

最佳答案

如果我遵循您的要求,那么您正在尝试从 URL 中提取 exampleproduct

这是用于完成此操作的正则表达式。第 1 组的名称应位于最后一个 / 之后和该斜杠之后的第一个 ? 之前。

^.*\/([^?]+)\?.*$

查看 regex 的示例

^           -- Beginning of line anchor
.*          -- find 0 or more characters. Note the * is greedy.
\/          -- Find a literal /.
([^?]+)     -- Capture everything that is not a question mark
\?          -- Find a literal question mark
.*          -- now match everything after the question mark
$           -- end of line anchor

这是在 Java 中使用它的一个简单示例。这是一个简单的示例,在使用之前需要进行修改。

String urlFull = "https://local.host.com/order/faces/Home/myorder/exampleproduct?_adf.ctrl-state=mfun9p14r_19";

Pattern pattern = Pattern.compile("^.*\\/([^?]+)\\?.*$");
Matcher matcher = pattern.matcher(urlFull);

matcher.find();

String p = matcher.group(1);
System.out.println(p);

我不明白为什么您编写的原始正则表达式有 .jspx?,但如果问题还有更多,您需要更新问题来解释。

关于java - 如何使用正则表达式提取此模式的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26818614/

相关文章:

java - 安卓:java.lang.IllegalStateException:已经连接

java - 在 Java 中使用套接字的 HTTP 1.1 持久连接

javascript - 将命令行拆分为参数

java - java中如何解析字符串的例子

android - 如何将多个分隔符传递给子字符串(Kotlin/Android)?

java - Spring 启动 YAML 配置 : Parametred keys

java - getValidationMode() 的 AbstractMethodErrorLjavax/persistence/ValidationMode

php - 正则表达式:如何匹配任何字符串直到空格,或者直到标点符号后跟空格?

ruby start_with?(), end_with?()

python - 定位距目标字符串 N 字符长距离最小的 "N Gram"个子字符串