在第三个正斜杠后面获取字符(" /") - 使用正则表达式

时间:2016-12-05 14:56:07

标签: java regex

我已经尝试从字符串中的第三个正斜杠(&#34; ###### Load needed package library(raster) library(sp) library(rgdal) library(tiff) library(ggplot2) library(maptools) library (zoo) library (signal) library(timeSeries) NDVI_STACK <- stack (jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec) fun <- function(x) { v=as.vector(x) z=substituteNA(v, type="mean") # from package timeSeries NDVI.ts2 = ts(z, start=c(2005,1), end=c(2005,12), frequency=12) x=sgolayfilt(NDVI.ts2, p=2, n=5, ts=30) NDVI.filtered <- calc(NDVI_STACK, fun, progress='text') #raster calculation process ...... &#34;)之后获取子字符串。

http://www.google.com/search?q=Regular+Expressions在停止之前?和#如果它们存在于字符串中。

我有正则表达式:

/

然而,它并不适用于每个字符串

我也提出了正则表达式:

Pattern regex = Pattern.compile(":\\/\\/[0-9a-zA-Z-\\.:]+(\\/)([^?#]*)$");
然而,这个人在第三个正斜杠之前抓住了所有东西(&#34; Pattern regex = Pattern.compile("(.*)?:\\/\\/[^#?]*); &#34;)。

我做错了什么? 感谢

1 个答案:

答案 0 :(得分:0)

这个正则表达式适用于java:

    public static void main(String[] args) throws Exception {
    String s = "http://www.google.com/search?q=Regular+Expressions";
    String regex = "(?:.*?/){2}.*?(/\\w+)(\\?|#).*"; // Don't capture anything upto the 3rd "/" then capture everything until you get a "?" or a "#" and then don't capture the rest. Replace everything with the captured value
    String str = s.replaceAll(regex, "$1");
    System.out.println(str);
    String s2 = "https://www.google.com/hello?test#";
    String str2 = s2.replaceAll(regex, "$1");
    System.out.println(str2);

}

O / P:

/search
/hello