【问题标题】:How to extract a substring using regex for this pattern如何为此模式使用正则表达式提取子字符串
【发布时间】:2015-01-05 06:28:59
【问题描述】:

我必须在/?之间提取一个字符串,即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"));

}

谢谢 拉杰

【问题讨论】:

标签: java regex substring


【解决方案1】:

如果我按照您的要求进行操作,那么您是在尝试从 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?,但如果问题还有更多,你需要更新问题来解释。

【讨论】:

    【解决方案2】:

    要在您的输入中匹配exampleproduct,这个基于前瞻的正则表达式将为您工作:

    [^/]+(?=\?)
    

    在 Java 代码中:

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

    RegEx Demo

    【讨论】:

      【解决方案3】:

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

      这个正则表达式找到一个问号并选择它后面的所有内容。

      【讨论】:

        【解决方案4】:

        我用你的路径尝试了这个模式,效果很好:([\w_-]*)(\.)*([\w_-]*)?(?=\?)

        如果您的文件名有文件结尾,它也会匹配。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-25
          相关资源
          最近更新 更多