[英]Java Regex to extract substring with optional trailing slash
Regex:正则表达式:
\/test\/(.*|\/?)
Input输入
/something/test/{abc}/listed
/something/test/{abc}
Expected预期的
{abc}
for both the inputs {abc}
用于两个输入
This should work for you :这应该适合你:
public static void main(String[] args) {
String s1 = "/something/test/{abc}/listed";
String s2 = "/something/test/{abc}";
System.out.println(s1.replaceAll("[^{]+(\\{\\w+\\}).*", "$1"));
System.out.println(s2.replaceAll("[^{]+(\\{\\w+\\}).*", "$1"));
}
O/P :开/关:
{abc}
{abc}
You need to capture all characters other than /
after /test/
:您需要在/test/
之后捕获除/
之外的所有字符:
String s = "/something/test/{abc}/listed";
Pattern pattern = Pattern.compile("/test/([^/]+)"); // or "/test/\\{([^/}]+)"
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
System.out.println(matcher.group(1));
}
See the online demo看在线演示
Details :详情:
/test/
- matches /test/
/test/
- 匹配/test/
([^/]+)
- matches and captures into Group 1 one or more ( +
) (but as many as possible, since +
is greedy) characters other than /
(due to the negated character class [^/]
). ([^/]+)
- 匹配并捕获到组 1 中的一个或多个 ( +
)(但尽可能多,因为+
是贪婪的)除/
之外的字符(由于否定字符类[^/]
)。 Note that in Java regex patterns you do not need to escape /
since it is not a special character and one needs no regex delimiters.请注意,在 Java 正则表达式模式中,您不需要转义/
因为它不是特殊字符并且不需要正则表达式分隔符。
正则表达式(作为 Java 字符串,带有双反斜杠):
".*\\/test\\/([^/]*).*"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.