我必须提取 /
和 ?
之间的字符串,即 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/