从URL提取字符串的一部分-Java Regex [英] Extract part of a string from a URL - Java Regex
本文介绍了从URL提取字符串的一部分-Java Regex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试提取'/'和'.之间的字符串.网址.例如,我有一个类似"some.com/part1/part2/part3/stringINeed.xyz"的URL.我需要从上面的URL中提取"stringINeed",即最后一个"/"和."之间的一个.没有其他的.
I'm trying to extract a string between '/' and '.' of a URL. For example, I have a URL like "some.com/part1/part2/part3/stringINeed.xyz". I need to extract "stringINeed" from the above URL, the one between last '/' and the '.' nothing else.
到目前为止,我尝试了以下操作,并给出了空的输出:
So far, I tried the following and it gives an empty output:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Extract
{
public static void main (String[] args) throws java.lang.Exception
{
String str = "part1/part2/part3/stringINeed.xyz" ;
Pattern pattern = Pattern.compile("/(.*?).");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
我的代码有什么问题.有人可以帮忙吗?
What is wrong with my code. Can anyone help?
推荐答案
使用此正则表达式:
[^/.]+(?=\.[^.]+$)
请参见演示.
在Java中:
Pattern regex = Pattern.compile("[^/.]+(?=\\.[^.]+$)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group();
}
说明
-
[^/.]+
匹配所有不是斜杠或点的字符 - 前瞻
(?=\.[^.]+)
断言,其后是一个点,后面跟着非点,然后是字符串的结尾
[^/.]+
matches any chars that are not a slash or a dot- The lookahead
(?=\.[^.]+)
asserts that what follows is a dot followed by non-dots and the end of the string
这篇关于从URL提取字符串的一部分-Java Regex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文