繁体   English   中英

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

[英]How to extract a substring using regex for this pattern

我必须在/和之间提取一个字符串? 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组的名称应在最后一个/之后以及第一个之前? 斜线之后。

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

查看正则表达式的示例

^           -- 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? ,但如果还有其他问题,则需要更新问题进行解释。

此模式可能对您\\?(.*)

这个正则表达式找到一个问号,然后选择所有内容。

我用您的路径尝试了这种模式,它运行良好: ([\\w_-]*)(\\.)*([\\w_-]*)?(?=\\?)

如果文件名的文件末尾也将匹配。

为了匹配输入中的exampleproduct ,此基于前瞻的正则表达式将为您工作:

[^/]+(?=\?)

在Java代码中:

Pattern pat = Pattern.compile("[^/]+(?=\\?)");

正则演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM