[英]how to define a regular expression that matches two different strings but not the third one
[英]How could I select a range of characters up until a third / is present and select all if there is no third / using regular expression
我需要在字符串中选择一个范围,直到第三个/
出现。
我目前有^([^\\/]*\\/[^\\/]*\\/[^\\/]*\\/
但这仅在字符串中超过 3 /
时才有效。理想情况下我需要选择直到第三个/
所有字符,如果没有第三个/
如果有人能想到解决这个问题的方法,那就太好了。
谢谢!
要匹配从/
第 3 次出现开始的子字符串,其中可能少于 3 /
s,您可以使用范围量词使用此正则表达式:
^(?:[^/]*/){0,3}
这个怎么运作:
^
我们从行首开始{0,3}
来匹配前面的组 0 到 3 次/
后跟/
的任何字符简单但有点低效的方法是:
String input = "your/input/should/be/there";
String[] parts = input.split("/");
if (parts.length > 2) {
return String.join("/", parts[0], parts[1], parts[2]);
} else {
return input;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.