![](/img/trans.png)
[英]regex to replace digits of a number with 0 (after 6th digit and before last 4th digit)
[英]splitting URL regex after 4th slash
我正在尝试将URL分成多个块。 我要的是一切,直到第5 /
。
我曾尝试环顾四周,但对regex还是陌生的,所以有点不知所措。
网址示例是:
http://daniel.mirimar.net.nz/Sites/reginald/DDD/CD
因此,我想从这里获得的信息是: http://daniel.mirimar.net.nz/Sites/reginald/
: http://daniel.mirimar.net.nz/Sites/reginald/
我怎样才能做到这一点?
简短而简洁总是很好
(?:.+?/){4}
(?:
-打开非捕获组 .+?/
-懒惰地匹配任何东西,直到/
)
-关闭非捕获组 {4}
-重复四次 使用这样的正则表达式:
^.*?\/\/[^\/]*\/[^\/]*\/[^\/]*
要么
^.*?\/(\/[^\/]*){3}
对于没有CRLF和URL且部分较少的检查:
^.*?\/(\/[^\/\n\r]*){1,3}
您可以通过以下方式更具体:
^https?:\/(\/[^\/\n\r]*){1,3}
有时, regex
可能会让人有些不知所措,特别是如果您不熟悉它。 它甚至会使代码更难阅读( 使用正则表达式的缺点 )。 现在,请不要误会我的意思,当任务足够简单时,我喜欢使用regex
。 IMO,您最好不用regex
来解决这个问题。 您可以设计一种方法来找到第5个“ /”的索引位置,然后仅返回子字符串。
就像是:
public static void main(String[] args) {
String url = "http://daniel.mirimar.net.nz/Sites/reginald/DDD/CD";
System.out.println(substringNthOccurrence(url, '/', 5));
}
public static String substringNthOccurrence(String string, char c, int n) {
if (n <= 0) {
return "";
}
int index = 0;
while (n-- > 0 && index != -1) {
index = string.indexOf(c, index + 1);
}
return index > -1 ? string.substring(0, index + 1) : "";
}
结果:
http://daniel.mirimar.net.nz/Sites/reginald/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.