java 提取特定模式后的子串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10908316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract substring after a certain pattern
提问by user1196969
I have the following string:
我有以下字符串:
http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true
How can I extract the part after 30/
? In this case, it's 32531a5d-b0b1-4a8b-9029-b48f0eb40a34
.I have another strings having same part upto 30/ and after that every string having different id upto next / which I want.
之后如何提取零件30/
?在这种情况下,它是32531a5d-b0b1-4a8b-9029-b48f0eb40a34
.I 有另一个具有相同部分的字符串,最多 30/,之后每个字符串都有不同的 id,直到我想要的下一个 /。
采纳答案by Untitled
split
function of String
class won't help you in this case, because it discards the delimiter and that's not what we want here. you need to make a pattern that looks behind. The look behind synatax is:
split
String
在这种情况下, class 的函数不会帮助你,因为它丢弃了分隔符,这不是我们想要的。你需要制作一个看起来后面的图案。Synatax 背后的外观是:
(?<=X)Y
Which identifies any Y
that is preceded by a X
.
它标识任何Y
以X
.
So in you case you need this pattern:
所以在你的情况下你需要这个模式:
(?<=30/).*
compile the pattern, match it with your input, find the match, and catch it:
编译模式,将其与您的输入匹配,找到匹配项并捕获它:
String input = "http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true";
Matcher matcher = Pattern.compile("(?<=30/).*").matcher(input);
matcher.find();
System.out.println(matcher.group());
回答by UVM
You can do like this:
你可以这样做:
String s = "http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true";
System.out.println(s.substring(s.indexOf("30/")+3, s.length()));
回答by jlengrand
Just for this one, or do you want a generic way to do it ?
只是为了这个,还是你想要一种通用的方法来做到这一点?
String[] out = mystring.split("/")
return out[out.length - 2]
I think the / is definitely the delimiter you are searching for. I can't see the problem you are talking about Alex
我认为 / 绝对是您正在搜索的分隔符。我看不出你在谈论亚历克斯的问题
EDIT : Ok, Python got me with indexes.
编辑:好的,Python 为我提供了索引。
回答by xiaofeng.li
Regular expression is the answer I think. However, how the expression is written depends on the data (url) format you want to process. Like this one:
正则表达式是我认为的答案。但是,表达式的编写方式取决于您要处理的数据(url)格式。像这个:
Pattern pat = Pattern.compile("/Content/SiteFiles/30/([a-z0-9\-]+)/.*");
Matcher m = pat.matcher("http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true");
if (m.find()) {
System.out.println(m.group(1));
}